<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>js手写面试题 | 孙志豪的博客</title><meta name="author" content="孙志豪"><meta name="copyright" content="孙志豪"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="1. 手写 Object.create思路：将传入的对象作为原型 123456function create(obj) &amp;#123;  function F() &amp;#123;&amp;#125;  F.prototype &#x3D; obj  return new F()&amp;#125;  2. 手写 instanceof 方法instanceof 运算符用于判断构造函数的 prototype 属性是否出现在对象">
<meta property="og:type" content="article">
<meta property="og:title" content="js手写面试题">
<meta property="og:url" content="https://szhihao.gitee.io/2022/10/11/07-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/js%E6%89%8B%E5%86%99%E4%BB%A3%E7%A0%81%E9%9D%A2%E8%AF%95%E9%A2%98/index.html">
<meta property="og:site_name" content="孙志豪的博客">
<meta property="og:description" content="1. 手写 Object.create思路：将传入的对象作为原型 123456function create(obj) &amp;#123;  function F() &amp;#123;&amp;#125;  F.prototype &#x3D; obj  return new F()&amp;#125;  2. 手写 instanceof 方法instanceof 运算符用于判断构造函数的 prototype 属性是否出现在对象">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://szhihao.gitee.io/img/%E5%A4%A9%E7%A9%BA.jpeg">
<meta property="article:published_time" content="2022-10-11T12:01:36.000Z">
<meta property="article:modified_time" content="2022-10-11T09:29:38.976Z">
<meta property="article:author" content="孙志豪">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://szhihao.gitee.io/img/%E5%A4%A9%E7%A9%BA.jpeg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://szhihao.gitee.io/2022/10/11/07-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/js%E6%89%8B%E5%86%99%E4%BB%A3%E7%A0%81%E9%9D%A2%E8%AF%95%E9%A2%98/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","languages":{"hits_empty":"We didn't find any results for the search: ${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'js手写面试题',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-10-11 17:29:38'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/img/%E5%A4%B4%E5%83%8F.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">44</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">15</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 生活</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 相册</span></a></li><li><a class="site-page child" href="/music/"><i class="fa-fw fa fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 影视</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/links/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/comment/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于笔者</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/img/%E5%A4%A9%E7%A9%BA.jpeg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">孙志豪的博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> Search</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 生活</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 相册</span></a></li><li><a class="site-page child" href="/music/"><i class="fa-fw fa fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 影视</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/links/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/comment/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于笔者</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">js手写面试题</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2022-10-11T12:01:36.000Z" title="Created 2022-10-11 20:01:36">2022-10-11</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2022-10-11T09:29:38.976Z" title="Updated 2022-10-11 17:29:38">2022-10-11</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/">核心js（手写篇）</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="js手写面试题"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><hr>
<p><img src= "" data-lazy-src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/6fd41339dfd14200bb006815eab31324~tplv-k3u1fbpfcp-watermark.awebp" alt="手写代码面试题.png"></p>
<h3 id="1-手写-Object-create"><a href="#1-手写-Object-create" class="headerlink" title="1. 手写 Object.create"></a>1. 手写 Object.create</h3><p>思路：将传入的对象作为原型</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">create</span>(<span class="params">obj</span>) &#123;</span><br><span class="line">  <span class="keyword">function</span> <span class="title function_">F</span>(<span class="params"></span>) &#123;&#125;</span><br><span class="line">  F.<span class="property"><span class="keyword">prototype</span></span> = obj</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="title function_">F</span>()</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="2-手写-instanceof-方法"><a href="#2-手写-instanceof-方法" class="headerlink" title="2. 手写 instanceof 方法"></a>2. 手写 instanceof 方法</h3><p>instanceof 运算符用于判断构造函数的 prototype 属性是否出现在对象的原型链中的任何位置。</p>
<p>实现步骤：</p>
<ol>
<li>首先获取类型的原型</li>
<li>然后获得对象的原型</li>
<li>然后一直循环判断对象的原型是否等于类型的原型，直到对象原型为 <code>null</code>，因为原型链最终为 <code>null</code></li>
</ol>
<p>具体实现：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">myInstanceof</span>(<span class="params">left, right</span>) &#123;</span><br><span class="line">  <span class="keyword">let</span> proto = <span class="title class_">Object</span>.<span class="title function_">getPrototypeOf</span>(left), <span class="comment">// 获取对象的原型</span></span><br><span class="line">      prototype = right.<span class="property"><span class="keyword">prototype</span></span>; <span class="comment">// 获取构造函数的 prototype 对象</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// 判断构造函数的 prototype 对象是否在对象的原型链上</span></span><br><span class="line">  <span class="keyword">while</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (!proto) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">if</span> (proto === prototype) <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line">    proto = <span class="title class_">Object</span>.<span class="title function_">getPrototypeOf</span>(proto);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="3-手写-new-操作符"><a href="#3-手写-new-操作符" class="headerlink" title="3. 手写 new 操作符"></a>3. 手写 new 操作符</h3><p>在调用 <code>new</code> 的过程中会发生以上四件事情：</p>
<p>（1）首先创建了一个新的空对象</p>
<p>（2）设置原型，将对象的原型设置为函数的 prototype 对象。</p>
<p>（3）让函数的 this 指向这个对象，执行构造函数的代码（为这个新对象添加属性）</p>
<p>（4）判断函数的返回值类型，如果是值类型，返回创建的对象。如果是引用类型，就返回这个引用类型的对象。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">objectFactory</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">let</span> newObject = <span class="literal">null</span>;</span><br><span class="line">  <span class="keyword">let</span> constructor = <span class="title class_">Array</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">shift</span>.<span class="title function_">call</span>(<span class="variable language_">arguments</span>);</span><br><span class="line">  <span class="keyword">let</span> result = <span class="literal">null</span>;</span><br><span class="line">  <span class="comment">// 判断参数是否是一个函数</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> constructor !== <span class="string">&quot;function&quot;</span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">error</span>(<span class="string">&quot;type error&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 新建一个空对象，对象的原型为构造函数的 prototype 对象</span></span><br><span class="line">  newObject = <span class="title class_">Object</span>.<span class="title function_">create</span>(constructor.<span class="property"><span class="keyword">prototype</span></span>);</span><br><span class="line">  <span class="comment">// 将 this 指向新建对象，并执行函数</span></span><br><span class="line">  result = constructor.<span class="title function_">apply</span>(newObject, <span class="variable language_">arguments</span>);</span><br><span class="line">  <span class="comment">// 判断返回对象</span></span><br><span class="line">  <span class="keyword">let</span> flag = result &amp;&amp; (<span class="keyword">typeof</span> result === <span class="string">&quot;object&quot;</span> || <span class="keyword">typeof</span> result === <span class="string">&quot;function&quot;</span>);</span><br><span class="line">  <span class="comment">// 判断返回结果</span></span><br><span class="line">  <span class="keyword">return</span> flag ? result : newObject;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 使用方法</span></span><br><span class="line"><span class="title function_">objectFactory</span>(构造函数, 初始化参数);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="4-手写-Promise"><a href="#4-手写-Promise" class="headerlink" title="4. 手写 Promise"></a>4. 手写 Promise</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="variable constant_">PENDING</span> = <span class="string">&quot;pending&quot;</span>;</span><br><span class="line"><span class="keyword">const</span> <span class="variable constant_">RESOLVED</span> = <span class="string">&quot;resolved&quot;</span>;</span><br><span class="line"><span class="keyword">const</span> <span class="variable constant_">REJECTED</span> = <span class="string">&quot;rejected&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">MyPromise</span>(<span class="params">fn</span>) &#123;</span><br><span class="line">  <span class="comment">// 保存初始化状态</span></span><br><span class="line">  <span class="keyword">var</span> self = <span class="variable language_">this</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 初始化状态</span></span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">state</span> = <span class="variable constant_">PENDING</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 用于保存 resolve 或者 rejected 传入的值</span></span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">value</span> = <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 用于保存 resolve 的回调函数</span></span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">resolvedCallbacks</span> = [];</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 用于保存 reject 的回调函数</span></span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">rejectedCallbacks</span> = [];</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 状态转变为 resolved 方法</span></span><br><span class="line">  <span class="keyword">function</span> <span class="title function_">resolve</span>(<span class="params">value</span>) &#123;</span><br><span class="line">    <span class="comment">// 判断传入元素是否为 Promise 值，如果是，则状态改变必须等待前一个状态改变后再进行改变</span></span><br><span class="line">    <span class="keyword">if</span> (value <span class="keyword">instanceof</span> <span class="title class_">MyPromise</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> value.<span class="title function_">then</span>(resolve, reject);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 保证代码的执行顺序为本轮事件循环的末尾</span></span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">      <span class="comment">// 只有状态为 pending 时才能转变，</span></span><br><span class="line">      <span class="keyword">if</span> (self.<span class="property">state</span> === <span class="variable constant_">PENDING</span>) &#123;</span><br><span class="line">        <span class="comment">// 修改状态</span></span><br><span class="line">        self.<span class="property">state</span> = <span class="variable constant_">RESOLVED</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 设置传入的值</span></span><br><span class="line">        self.<span class="property">value</span> = value;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 执行回调函数</span></span><br><span class="line">        self.<span class="property">resolvedCallbacks</span>.<span class="title function_">forEach</span>(<span class="function"><span class="params">callback</span> =&gt;</span> &#123;</span><br><span class="line">          <span class="title function_">callback</span>(value);</span><br><span class="line">        &#125;);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;, <span class="number">0</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 状态转变为 rejected 方法</span></span><br><span class="line">  <span class="keyword">function</span> <span class="title function_">reject</span>(<span class="params">value</span>) &#123;</span><br><span class="line">    <span class="comment">// 保证代码的执行顺序为本轮事件循环的末尾</span></span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">      <span class="comment">// 只有状态为 pending 时才能转变</span></span><br><span class="line">      <span class="keyword">if</span> (self.<span class="property">state</span> === <span class="variable constant_">PENDING</span>) &#123;</span><br><span class="line">        <span class="comment">// 修改状态</span></span><br><span class="line">        self.<span class="property">state</span> = <span class="variable constant_">REJECTED</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 设置传入的值</span></span><br><span class="line">        self.<span class="property">value</span> = value;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 执行回调函数</span></span><br><span class="line">        self.<span class="property">rejectedCallbacks</span>.<span class="title function_">forEach</span>(<span class="function"><span class="params">callback</span> =&gt;</span> &#123;</span><br><span class="line">          <span class="title function_">callback</span>(value);</span><br><span class="line">        &#125;);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;, <span class="number">0</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 将两个方法传入函数执行</span></span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="title function_">fn</span>(resolve, reject);</span><br><span class="line">  &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">    <span class="comment">// 遇到错误时，捕获错误，执行 reject 函数</span></span><br><span class="line">    <span class="title function_">reject</span>(e);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="title class_">MyPromise</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">then</span> = <span class="keyword">function</span>(<span class="params">onResolved, onRejected</span>) &#123;</span><br><span class="line">  <span class="comment">// 首先判断两个参数是否为函数类型，因为这两个参数是可选参数</span></span><br><span class="line">  onResolved =</span><br><span class="line">    <span class="keyword">typeof</span> onResolved === <span class="string">&quot;function&quot;</span></span><br><span class="line">      ? onResolved</span><br><span class="line">      : <span class="keyword">function</span>(<span class="params">value</span>) &#123;</span><br><span class="line">          <span class="keyword">return</span> value;</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">  onRejected =</span><br><span class="line">    <span class="keyword">typeof</span> onRejected === <span class="string">&quot;function&quot;</span></span><br><span class="line">      ? onRejected</span><br><span class="line">      : <span class="keyword">function</span>(<span class="params">error</span>) &#123;</span><br><span class="line">          <span class="keyword">throw</span> error;</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 如果是等待状态，则将函数加入对应列表中</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">state</span> === <span class="variable constant_">PENDING</span>) &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">resolvedCallbacks</span>.<span class="title function_">push</span>(onResolved);</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">rejectedCallbacks</span>.<span class="title function_">push</span>(onRejected);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 如果状态已经凝固，则直接执行对应状态的函数</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">state</span> === <span class="variable constant_">RESOLVED</span>) &#123;</span><br><span class="line">    <span class="title function_">onResolved</span>(<span class="variable language_">this</span>.<span class="property">value</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">state</span> === <span class="variable constant_">REJECTED</span>) &#123;</span><br><span class="line">    <span class="title function_">onRejected</span>(<span class="variable language_">this</span>.<span class="property">value</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="5-手写-Promise-then"><a href="#5-手写-Promise-then" class="headerlink" title="5. 手写 Promise.then"></a>5. 手写 Promise.then</h3><p><code>then</code> 方法返回一个新的 <code>promise</code> 实例，为了在 <code>promise</code> 状态发生变化时（<code>resolve</code> &#x2F; <code>reject</code> 被调用时）再执行 <code>then</code> 里的函数，我们使用一个 <code>callbacks</code> 数组先把传给then的函数暂存起来，等状态改变时再调用。</p>
<p><strong>那么，怎么保证后一个 *<em><code>\*\*then\*\*</code>*</em> 里的方法在前一个 **<code>\*\*then\*\*</code>**（可能是异步）结束之后再执行呢？</strong> 我们可以将传给 <code>then</code> 的函数和新 <code>promise</code> 的 <code>resolve</code> 一起 <code>push</code> 到前一个 <code>promise</code> 的 <code>callbacks</code> 数组中，达到承前启后的效果：</p>
<ul>
<li>承前：当前一个 <code>promise</code> 完成后，调用其 <code>resolve</code> 变更状态，在这个 <code>resolve</code> 里会依次调用 <code>callbacks</code> 里的回调，这样就执行了 <code>then</code> 里的方法了</li>
<li>启后：上一步中，当 <code>then</code> 里的方法执行完成后，返回一个结果，如果这个结果是个简单的值，就直接调用新 <code>promise</code> 的 <code>resolve</code>，让其状态变更，这又会依次调用新 <code>promise</code> 的 <code>callbacks</code> 数组里的方法，循环往复。。如果返回的结果是个 <code>promise</code>，则需要等它完成之后再触发新 <code>promise</code> 的 <code>resolve</code>，所以可以在其结果的 <code>then</code> 里调用新 <code>promise</code> 的 <code>resolve</code></li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">then</span>(<span class="params">onFulfilled, onReject</span>)&#123;</span><br><span class="line">    <span class="comment">// 保存前一个promise的this</span></span><br><span class="line">    <span class="keyword">const</span> self = <span class="variable language_">this</span>; </span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">MyPromise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="comment">// 封装前一个promise成功时执行的函数</span></span><br><span class="line">      <span class="keyword">let</span> <span class="title function_">fulfilled</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">        <span class="keyword">try</span>&#123;</span><br><span class="line">          <span class="keyword">const</span> result = <span class="title function_">onFulfilled</span>(self.<span class="property">value</span>); <span class="comment">// 承前</span></span><br><span class="line">          <span class="keyword">return</span> result <span class="keyword">instanceof</span> <span class="title class_">MyPromise</span>? result.<span class="title function_">then</span>(resolve, reject) : <span class="title function_">resolve</span>(result); <span class="comment">//启后</span></span><br><span class="line">        &#125;<span class="keyword">catch</span>(err)&#123;</span><br><span class="line">          <span class="title function_">reject</span>(err)</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 封装前一个promise失败时执行的函数</span></span><br><span class="line">      <span class="keyword">let</span> <span class="title function_">rejected</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">        <span class="keyword">try</span>&#123;</span><br><span class="line">          <span class="keyword">const</span> result = <span class="title function_">onReject</span>(self.<span class="property">reason</span>);</span><br><span class="line">          <span class="keyword">return</span> result <span class="keyword">instanceof</span> <span class="title class_">MyPromise</span>? result.<span class="title function_">then</span>(resolve, reject) : <span class="title function_">reject</span>(result);</span><br><span class="line">        &#125;<span class="keyword">catch</span>(err)&#123;</span><br><span class="line">          <span class="title function_">reject</span>(err)</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">switch</span>(self.<span class="property">status</span>)&#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="attr">PENDING</span>: </span><br><span class="line">          self.<span class="property">onFulfilledCallbacks</span>.<span class="title function_">push</span>(fulfilled);</span><br><span class="line">          self.<span class="property">onRejectedCallbacks</span>.<span class="title function_">push</span>(rejected);</span><br><span class="line">          <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> <span class="attr">FULFILLED</span>:</span><br><span class="line">          <span class="title function_">fulfilled</span>();</span><br><span class="line">          <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> <span class="attr">REJECT</span>:</span><br><span class="line">          <span class="title function_">rejected</span>();</span><br><span class="line">          <span class="keyword">break</span>;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">   &#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><strong>注意：</strong></p>
<ul>
<li>连续多个 <code>then</code> 里的回调方法是同步注册的，但注册到了不同的 <code>callbacks</code> 数组中，因为每次 <code>then</code> 都返回新的 <code>promise</code> 实例（参考上面的例子和图）</li>
<li>注册完成后开始执行构造函数中的异步事件，异步完成之后依次调用 <code>callbacks</code> 数组中提前注册的回调</li>
</ul>
<h3 id="6-手写-Promise-all"><a href="#6-手写-Promise-all" class="headerlink" title="6. 手写 Promise.all"></a>6. 手写 Promise.all</h3><p><strong>1) 核心思路</strong></p>
<ol>
<li>接收一个 Promise 实例的数组或具有 Iterator 接口的对象作为参数</li>
<li>这个方法返回一个新的 promise 对象，</li>
<li>遍历传入的参数，用Promise.resolve()将参数”包一层”，使其变成一个promise对象</li>
<li>参数所有回调成功才是成功，返回值数组与参数顺序一致</li>
<li>参数数组其中一个失败，则触发失败状态，第一个触发失败的 Promise 错误信息作为 Promise.all 的错误信息。</li>
</ol>
<p><strong>2）实现代码</strong></p>
<p>一般来说，Promise.all 用来处理多个并发请求，也是为了页面数据构造的方便，将一个页面所用到的在不同接口的数据一起请求过来，不过，如果其中一个接口失败了，多个请求也就失败了，页面可能啥也出不来，这就看当前页面的耦合程度了</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">promiseAll</span>(<span class="params">promises</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span>(<span class="params">resolve, reject</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span>(!<span class="title class_">Array</span>.<span class="title function_">isArray</span>(promises))&#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">TypeError</span>(<span class="string">`argument must be a array`</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">var</span> resolvedCounter = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">var</span> promiseNum = promises.<span class="property">length</span>;</span><br><span class="line">    <span class="keyword">var</span> resolvedResult = [];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; promiseNum; i++) &#123;</span><br><span class="line">      <span class="title class_">Promise</span>.<span class="title function_">resolve</span>(promises[i]).<span class="title function_">then</span>(<span class="function"><span class="params">value</span>=&gt;</span>&#123;</span><br><span class="line">        resolvedCounter++;</span><br><span class="line">        resolvedResult[i] = value;</span><br><span class="line">        <span class="keyword">if</span> (resolvedCounter == promiseNum) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="title function_">resolve</span>(resolvedResult)</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;,<span class="function"><span class="params">error</span>=&gt;</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="title function_">reject</span>(error)</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// test</span></span><br><span class="line"><span class="keyword">let</span> p1 = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="title function_">resolve</span>(<span class="number">1</span>)</span><br><span class="line">    &#125;, <span class="number">1000</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">let</span> p2 = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="title function_">resolve</span>(<span class="number">2</span>)</span><br><span class="line">    &#125;, <span class="number">2000</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">let</span> p3 = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span> (<span class="params">resolve, reject</span>) &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="title function_">resolve</span>(<span class="number">3</span>)</span><br><span class="line">    &#125;, <span class="number">3000</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="title function_">promiseAll</span>([p3, p1, p2]).<span class="title function_">then</span>(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res) <span class="comment">// [3, 1, 2]</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="7-手写-Promise-race"><a href="#7-手写-Promise-race" class="headerlink" title="7. 手写 Promise.race"></a>7. 手写 Promise.race</h3><p>该方法的参数是 Promise 实例数组, 然后其 then 注册的回调方法是数组中的某一个 Promise 的状态变为 fulfilled 的时候就执行. 因为 Promise 的状态<strong>只能改变一次</strong>, 那么我们只需要把 Promise.race 中产生的 Promise 对象的 resolve 方法, 注入到数组中的每一个 Promise 实例中的回调函数中即可.</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">Promise</span>.<span class="property">race</span> = <span class="keyword">function</span> (<span class="params">args</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>, len = args.<span class="property">length</span>; i &lt; len; i++) &#123;</span><br><span class="line">      args[i].<span class="title function_">then</span>(resolve, reject)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="8-手写防抖函数"><a href="#8-手写防抖函数" class="headerlink" title="8. 手写防抖函数"></a>8. 手写防抖函数</h3><p>函数防抖是指在事件被触发 n 秒后再执行回调，如果在这 n 秒内事件又被触发，则重新计时。这可以使用在一些点击请求的事件上，避免因为用户的多次点击向后端发送多次请求。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 函数防抖的实现</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">debounce</span>(<span class="params">fn, wait</span>) &#123;</span><br><span class="line">  <span class="keyword">let</span> timer = <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> context = <span class="variable language_">this</span>,</span><br><span class="line">        args = <span class="variable language_">arguments</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 如果此时存在定时器的话，则取消之前的定时器重新记时</span></span><br><span class="line">    <span class="keyword">if</span> (timer) &#123;</span><br><span class="line">      <span class="built_in">clearTimeout</span>(timer);</span><br><span class="line">      timer = <span class="literal">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 设置定时器，使事件间隔指定事件后执行</span></span><br><span class="line">    timer = <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">      fn.<span class="title function_">apply</span>(context, args);</span><br><span class="line">    &#125;, wait);</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="9-手写节流函数"><a href="#9-手写节流函数" class="headerlink" title="9. 手写节流函数"></a>9. 手写节流函数</h3><p>函数节流是指规定一个单位时间，在这个单位时间内，只能有一次触发事件的回调函数执行，如果在同一个单位时间内某事件被触发多次，只有一次能生效。节流可以使用在 scroll 函数的事件监听上，通过事件节流来降低事件调用的频率。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 函数节流的实现;</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">throttle</span>(<span class="params">fn, delay</span>) &#123;</span><br><span class="line">  <span class="keyword">let</span> curTime = <span class="title class_">Date</span>.<span class="title function_">now</span>();</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> context = <span class="variable language_">this</span>,</span><br><span class="line">        args = <span class="variable language_">arguments</span>,</span><br><span class="line">        nowTime = <span class="title class_">Date</span>.<span class="title function_">now</span>();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 如果两次时间间隔超过了指定时间，则执行函数。</span></span><br><span class="line">    <span class="keyword">if</span> (nowTime - curTime &gt;= delay) &#123;</span><br><span class="line">      curTime = <span class="title class_">Date</span>.<span class="title function_">now</span>();</span><br><span class="line">      <span class="keyword">return</span> fn.<span class="title function_">apply</span>(context, args);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="10-手写类型判断函数"><a href="#10-手写类型判断函数" class="headerlink" title="10. 手写类型判断函数"></a>10. 手写类型判断函数</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">getType</span>(<span class="params">value</span>) &#123;</span><br><span class="line">  <span class="comment">// 判断数据是 null 的情况</span></span><br><span class="line">  <span class="keyword">if</span> (value === <span class="literal">null</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> value + <span class="string">&quot;&quot;</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 判断数据是引用类型的情况</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> value === <span class="string">&quot;object&quot;</span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> valueClass = <span class="title class_">Object</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">toString</span>.<span class="title function_">call</span>(value),</span><br><span class="line">      type = valueClass.<span class="title function_">split</span>(<span class="string">&quot; &quot;</span>)[<span class="number">1</span>].<span class="title function_">split</span>(<span class="string">&quot;&quot;</span>);</span><br><span class="line">    type.<span class="title function_">pop</span>();</span><br><span class="line">    <span class="keyword">return</span> type.<span class="title function_">join</span>(<span class="string">&quot;&quot;</span>).<span class="title function_">toLowerCase</span>();</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// 判断数据是基本数据类型的情况和函数的情况</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">typeof</span> value;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="11-手写-call-函数"><a href="#11-手写-call-函数" class="headerlink" title="11. 手写 call 函数"></a>11. 手写 call 函数</h3><p>call 函数的实现步骤：</p>
<ol>
<li>判断调用对象是否为函数，即使我们是定义在函数的原型上的，但是可能出现使用 call 等方式调用的情况。</li>
<li>判断传入上下文对象是否存在，如果不存在，则设置为 window 。</li>
<li>处理传入的参数，截取第一个参数后的所有参数。</li>
<li>将函数作为上下文对象的一个属性。</li>
<li>使用上下文对象来调用这个方法，并保存返回结果。</li>
<li>删除刚才新增的属性。</li>
<li>返回结果。</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// call函数实现</span></span><br><span class="line"><span class="title class_">Function</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">myCall</span> = <span class="keyword">function</span>(<span class="params">context</span>) &#123;</span><br><span class="line">  <span class="comment">// 判断调用对象</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> <span class="variable language_">this</span> !== <span class="string">&quot;function&quot;</span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">error</span>(<span class="string">&quot;type error&quot;</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 获取参数</span></span><br><span class="line">  <span class="keyword">let</span> args = [...<span class="variable language_">arguments</span>].<span class="title function_">slice</span>(<span class="number">1</span>),</span><br><span class="line">      result = <span class="literal">null</span>;</span><br><span class="line">  <span class="comment">// 判断 context 是否传入，如果未传入则设置为 window</span></span><br><span class="line">  context = context || <span class="variable language_">window</span>;</span><br><span class="line">  <span class="comment">// 将调用函数设为对象的方法</span></span><br><span class="line">  context.<span class="property">fn</span> = <span class="variable language_">this</span>;</span><br><span class="line">  <span class="comment">// 调用函数</span></span><br><span class="line">  result = context.<span class="title function_">fn</span>(...args);</span><br><span class="line">  <span class="comment">// 将属性删除</span></span><br><span class="line">  <span class="keyword">delete</span> context.<span class="property">fn</span>;</span><br><span class="line">  <span class="keyword">return</span> result;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="12-手写-apply-函数"><a href="#12-手写-apply-函数" class="headerlink" title="12. 手写 apply 函数"></a>12. 手写 apply 函数</h3><p>apply 函数的实现步骤：</p>
<ol>
<li>判断调用对象是否为函数，即使我们是定义在函数的原型上的，但是可能出现使用 call 等方式调用的情况。</li>
<li>判断传入上下文对象是否存在，如果不存在，则设置为 window 。</li>
<li>将函数作为上下文对象的一个属性。</li>
<li>判断参数值是否传入</li>
<li>使用上下文对象来调用这个方法，并保存返回结果。</li>
<li>删除刚才新增的属性</li>
<li>返回结果</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// apply 函数实现</span></span><br><span class="line"><span class="title class_">Function</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">myApply</span> = <span class="keyword">function</span>(<span class="params">context</span>) &#123;</span><br><span class="line">  <span class="comment">// 判断调用对象是否为函数</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> <span class="variable language_">this</span> !== <span class="string">&quot;function&quot;</span>) &#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">TypeError</span>(<span class="string">&quot;Error&quot;</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">let</span> result = <span class="literal">null</span>;</span><br><span class="line">  <span class="comment">// 判断 context 是否存在，如果未传入则为 window</span></span><br><span class="line">  context = context || <span class="variable language_">window</span>;</span><br><span class="line">  <span class="comment">// 将函数设为对象的方法</span></span><br><span class="line">  context.<span class="property">fn</span> = <span class="variable language_">this</span>;</span><br><span class="line">  <span class="comment">// 调用方法</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="variable language_">arguments</span>[<span class="number">1</span>]) &#123;</span><br><span class="line">    result = context.<span class="title function_">fn</span>(...<span class="variable language_">arguments</span>[<span class="number">1</span>]);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    result = context.<span class="title function_">fn</span>();</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 将属性删除</span></span><br><span class="line">  <span class="keyword">delete</span> context.<span class="property">fn</span>;</span><br><span class="line">  <span class="keyword">return</span> result;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="13-手写-bind-函数"><a href="#13-手写-bind-函数" class="headerlink" title="13. 手写 bind 函数"></a>13. 手写 bind 函数</h3><p>bind 函数的实现步骤：</p>
<ol>
<li>判断调用对象是否为函数，即使我们是定义在函数的原型上的，但是可能出现使用 call 等方式调用的情况。</li>
<li>保存当前函数的引用，获取其余传入参数值。</li>
<li>创建一个函数返回</li>
<li>函数内部使用 apply 来绑定函数调用，需要判断函数作为构造函数的情况，这个时候需要传入当前函数的 this 给 apply 调用，其余情况都传入指定的上下文对象。</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// bind 函数实现</span></span><br><span class="line"><span class="title class_">Function</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">myBind</span> = <span class="keyword">function</span>(<span class="params">context</span>) &#123;</span><br><span class="line">  <span class="comment">// 判断调用对象是否为函数</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> <span class="variable language_">this</span> !== <span class="string">&quot;function&quot;</span>) &#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">TypeError</span>(<span class="string">&quot;Error&quot;</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 获取参数</span></span><br><span class="line">  <span class="keyword">var</span> args = [...<span class="variable language_">arguments</span>].<span class="title function_">slice</span>(<span class="number">1</span>),</span><br><span class="line">      fn = <span class="variable language_">this</span>;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">function</span> <span class="title function_">Fn</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="comment">// 根据调用方式，传入不同绑定值</span></span><br><span class="line">    <span class="keyword">return</span> fn.<span class="title function_">apply</span>(</span><br><span class="line">      <span class="variable language_">this</span> <span class="keyword">instanceof</span> <span class="title class_">Fn</span> ? <span class="variable language_">this</span> : context,</span><br><span class="line">      args.<span class="title function_">concat</span>(...<span class="variable language_">arguments</span>)</span><br><span class="line">    );</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="14-函数柯里化的实现"><a href="#14-函数柯里化的实现" class="headerlink" title="14. 函数柯里化的实现"></a>14. 函数柯里化的实现</h3><p>函数柯里化指的是一种将使用多个参数的一个函数转换成一系列使用一个参数的函数的技术。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">curry</span>(<span class="params">fn, args</span>) &#123;</span><br><span class="line">  <span class="comment">// 获取函数需要的参数长度</span></span><br><span class="line">  <span class="keyword">let</span> length = fn.<span class="property">length</span>;</span><br><span class="line"></span><br><span class="line">  args = args || [];</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> subArgs = args.<span class="title function_">slice</span>(<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 拼接得到现有的所有参数</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="variable language_">arguments</span>.<span class="property">length</span>; i++) &#123;</span><br><span class="line">      subArgs.<span class="title function_">push</span>(<span class="variable language_">arguments</span>[i]);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 判断参数的长度是否已经满足函数所需参数的长度</span></span><br><span class="line">    <span class="keyword">if</span> (subArgs.<span class="property">length</span> &gt;= length) &#123;</span><br><span class="line">      <span class="comment">// 如果满足，执行函数</span></span><br><span class="line">      <span class="keyword">return</span> fn.<span class="title function_">apply</span>(<span class="variable language_">this</span>, subArgs);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// 如果不满足，递归返回科里化的函数，等待参数的传入</span></span><br><span class="line">      <span class="keyword">return</span> curry.<span class="title function_">call</span>(<span class="variable language_">this</span>, fn, subArgs);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// es6 实现</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">curry</span>(<span class="params">fn, ...args</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> fn.<span class="property">length</span> &lt;= args.<span class="property">length</span> ? <span class="title function_">fn</span>(...args) : curry.<span class="title function_">bind</span>(<span class="literal">null</span>, fn, ...args);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="15-实现AJAX请求"><a href="#15-实现AJAX请求" class="headerlink" title="15. 实现AJAX请求"></a>15. 实现AJAX请求</h3><p>AJAX是 Asynchronous JavaScript and XML 的缩写，指的是通过 JavaScript 的 异步通信，从服务器获取 XML 文档从中提取数据，再更新当前网页的对应部分，而不用刷新整个网页。</p>
<p>创建AJAX请求的步骤：</p>
<ul>
<li><strong>创建一个 XMLHttpRequest 对象。</strong></li>
<li>在这个对象上<strong>使用 open 方法创建一个 HTTP 请求</strong>，open 方法所需要的参数是请求的方法、请求的地址、是否异步和用户的认证信息。</li>
<li>在发起请求前，可以为这个对象<strong>添加一些信息和监听函数</strong>。比如说可以通过 setRequestHeader 方法来为请求添加头信息。还可以为这个对象添加一个状态监听函数。一个 XMLHttpRequest 对象一共有 5 个状态，当它的状态变化时会触发onreadystatechange 事件，可以通过设置监听函数，来处理请求成功后的结果。当对象的 readyState 变为 4 的时候，代表服务器返回的数据接收完成，这个时候可以通过判断请求的状态，如果状态是 2xx 或者 304 的话则代表返回正常。这个时候就可以通过 response 中的数据来对页面进行更新了。</li>
<li>当对象的属性和监听函数设置完成后，最后调<strong>用 sent 方法来向服务器发起请求</strong>，可以传入参数作为发送的数据体。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="variable constant_">SERVER_URL</span> = <span class="string">&quot;/server&quot;</span>;</span><br><span class="line"><span class="keyword">let</span> xhr = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span><br><span class="line"><span class="comment">// 创建 Http 请求</span></span><br><span class="line">xhr.<span class="title function_">open</span>(<span class="string">&quot;GET&quot;</span>, <span class="variable constant_">SERVER_URL</span>, <span class="literal">true</span>);</span><br><span class="line"><span class="comment">// 设置状态监听函数</span></span><br><span class="line">xhr.<span class="property">onreadystatechange</span> = <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">readyState</span> !== <span class="number">4</span>) <span class="keyword">return</span>;</span><br><span class="line">  <span class="comment">// 当请求成功时</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">status</span> === <span class="number">200</span>) &#123;</span><br><span class="line">    <span class="title function_">handle</span>(<span class="variable language_">this</span>.<span class="property">response</span>);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">error</span>(<span class="variable language_">this</span>.<span class="property">statusText</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">// 设置请求失败时的监听函数</span></span><br><span class="line">xhr.<span class="property">onerror</span> = <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">error</span>(<span class="variable language_">this</span>.<span class="property">statusText</span>);</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">// 设置请求头信息</span></span><br><span class="line">xhr.<span class="property">responseType</span> = <span class="string">&quot;json&quot;</span>;</span><br><span class="line">xhr.<span class="title function_">setRequestHeader</span>(<span class="string">&quot;Accept&quot;</span>, <span class="string">&quot;application/json&quot;</span>);</span><br><span class="line"><span class="comment">// 发送 Http 请求</span></span><br><span class="line">xhr.<span class="title function_">send</span>(<span class="literal">null</span>);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="16-使用Promise封装AJAX请求"><a href="#16-使用Promise封装AJAX请求" class="headerlink" title="16. 使用Promise封装AJAX请求"></a>16. 使用Promise封装AJAX请求</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// promise 封装实现：</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">getJSON</span>(<span class="params">url</span>) &#123;</span><br><span class="line">  <span class="comment">// 创建一个 promise 对象</span></span><br><span class="line">  <span class="keyword">let</span> promise = <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="keyword">function</span>(<span class="params">resolve, reject</span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> xhr = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span><br><span class="line">    <span class="comment">// 新建一个 http 请求</span></span><br><span class="line">    xhr.<span class="title function_">open</span>(<span class="string">&quot;GET&quot;</span>, url, <span class="literal">true</span>);</span><br><span class="line">    <span class="comment">// 设置状态的监听函数</span></span><br><span class="line">    xhr.<span class="property">onreadystatechange</span> = <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">      <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">readyState</span> !== <span class="number">4</span>) <span class="keyword">return</span>;</span><br><span class="line">      <span class="comment">// 当请求成功或失败时，改变 promise 的状态</span></span><br><span class="line">      <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">status</span> === <span class="number">200</span>) &#123;</span><br><span class="line">        <span class="title function_">resolve</span>(<span class="variable language_">this</span>.<span class="property">response</span>);</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="title function_">reject</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="variable language_">this</span>.<span class="property">statusText</span>));</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="comment">// 设置错误监听函数</span></span><br><span class="line">    xhr.<span class="property">onerror</span> = <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">      <span class="title function_">reject</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="variable language_">this</span>.<span class="property">statusText</span>));</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="comment">// 设置响应的数据类型</span></span><br><span class="line">    xhr.<span class="property">responseType</span> = <span class="string">&quot;json&quot;</span>;</span><br><span class="line">    <span class="comment">// 设置请求头信息</span></span><br><span class="line">    xhr.<span class="title function_">setRequestHeader</span>(<span class="string">&quot;Accept&quot;</span>, <span class="string">&quot;application/json&quot;</span>);</span><br><span class="line">    <span class="comment">// 发送 http 请求</span></span><br><span class="line">    xhr.<span class="title function_">send</span>(<span class="literal">null</span>);</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">return</span> promise;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="17-实现浅拷贝"><a href="#17-实现浅拷贝" class="headerlink" title="17. 实现浅拷贝"></a>17. 实现浅拷贝</h3><p>浅拷贝是指，一个新的对象对原始对象的属性值进行精确地拷贝，如果拷贝的是基本数据类型，拷贝的就是基本数据类型的值，如果是引用数据类型，拷贝的就是内存地址。如果其中一个对象的引用内存地址发生改变，另一个对象也会发生变化。</p>
<h4 id="（1）Object-assign"><a href="#（1）Object-assign" class="headerlink" title="（1）Object.assign()"></a>（1）Object.assign()</h4><p><code>Object.assign()</code>是ES6中对象的拷贝方法，接受的第一个参数是目标对象，其余参数是源对象，用法：<code>Object.assign(target, source_1, ···)</code>，该方法可以实现浅拷贝，也可以实现一维对象的深拷贝。</p>
<p><strong>注意：</strong></p>
<ul>
<li>如果目标对象和源对象有同名属性，或者多个源对象有同名属性，则后面的属性会覆盖前面的属性。</li>
<li>如果该函数只有一个参数，当参数为对象时，直接返回该对象；当参数不是对象时，会先将参数转为对象然后返回。</li>
<li>因为<code>null</code> 和 <code>undefined</code> 不能转化为对象，所以第一个参数不能为<code>null</code>或 <code>undefined</code>，会报错。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> target = &#123;<span class="attr">a</span>: <span class="number">1</span>&#125;;</span><br><span class="line"><span class="keyword">let</span> object2 = &#123;<span class="attr">b</span>: <span class="number">2</span>&#125;;</span><br><span class="line"><span class="keyword">let</span> object3 = &#123;<span class="attr">c</span>: <span class="number">3</span>&#125;;</span><br><span class="line"><span class="title class_">Object</span>.<span class="title function_">assign</span>(target,object2,object3);  </span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(target);  <span class="comment">// &#123;a: 1, b: 2, c: 3&#125;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="（2）扩展运算符"><a href="#（2）扩展运算符" class="headerlink" title="（2）扩展运算符"></a>（2）扩展运算符</h4><p>使用扩展运算符可以在构造字面量对象的时候，进行属性的拷贝。语法：<code>let cloneObj = &#123; ...obj &#125;;</code></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> obj1 = &#123;<span class="attr">a</span>:<span class="number">1</span>,<span class="attr">b</span>:&#123;<span class="attr">c</span>:<span class="number">1</span>&#125;&#125;</span><br><span class="line"><span class="keyword">let</span> obj2 = &#123;...obj1&#125;;</span><br><span class="line">obj1.<span class="property">a</span> = <span class="number">2</span>;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(obj1); <span class="comment">//&#123;a:2,b:&#123;c:1&#125;&#125;</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(obj2); <span class="comment">//&#123;a:1,b:&#123;c:1&#125;&#125;</span></span><br><span class="line">obj1.<span class="property">b</span>.<span class="property">c</span> = <span class="number">2</span>;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(obj1); <span class="comment">//&#123;a:2,b:&#123;c:2&#125;&#125;</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(obj2); <span class="comment">//&#123;a:1,b:&#123;c:2&#125;&#125;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="（3）数组方法实现数组浅拷贝"><a href="#（3）数组方法实现数组浅拷贝" class="headerlink" title="（3）数组方法实现数组浅拷贝"></a>（3）数组方法实现数组浅拷贝</h4><h6 id="1）Array-prototype-slice"><a href="#1）Array-prototype-slice" class="headerlink" title="1）Array.prototype.slice"></a><strong>1）Array.prototype.slice</strong></h6><ul>
<li><code>slice()</code>方法是JavaScript数组的一个方法，这个方法可以从已有数组中返回选定的元素：用法：<code>array.slice(start, end)</code>，该方法不会改变原始数组。</li>
<li>该方法有两个参数，两个参数都可选，如果两个参数都不写，就可以实现一个数组的浅拷贝。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>];</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(arr.<span class="title function_">slice</span>()); <span class="comment">// [1,2,3,4]</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(arr.<span class="title function_">slice</span>() === arr); <span class="comment">//false</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h6 id="2）Array-prototype-concat"><a href="#2）Array-prototype-concat" class="headerlink" title="2）Array.prototype.concat"></a><strong>2）Array.prototype.concat</strong></h6><ul>
<li><code>concat()</code> 方法用于合并两个或多个数组。此方法不会更改现有数组，而是返回一个新数组。</li>
<li>该方法有两个参数，两个参数都可选，如果两个参数都不写，就可以实现一个数组的浅拷贝。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>];</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(arr.<span class="title function_">concat</span>()); <span class="comment">// [1,2,3,4]</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(arr.<span class="title function_">concat</span>() === arr); <span class="comment">//false</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="（4）手写实现浅拷贝"><a href="#（4）手写实现浅拷贝" class="headerlink" title="（4）手写实现浅拷贝"></a>（4）手写实现浅拷贝</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 浅拷贝的实现;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">shallowCopy</span>(<span class="params">object</span>) &#123;</span><br><span class="line">  <span class="comment">// 只拷贝对象</span></span><br><span class="line">  <span class="keyword">if</span> (!object || <span class="keyword">typeof</span> object !== <span class="string">&quot;object&quot;</span>) <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 根据 object 的类型判断是新建一个数组还是对象</span></span><br><span class="line">  <span class="keyword">let</span> newObject = <span class="title class_">Array</span>.<span class="title function_">isArray</span>(object) ? [] : &#123;&#125;;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 遍历 object，并且判断是 object 的属性才拷贝</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> key <span class="keyword">in</span> object) &#123;</span><br><span class="line">    <span class="keyword">if</span> (object.<span class="title function_">hasOwnProperty</span>(key)) &#123;</span><br><span class="line">      newObject[key] = object[key];</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> newObject;</span><br><span class="line">&#125;<span class="comment">// 浅拷贝的实现;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">shallowCopy</span>(<span class="params">object</span>) &#123;</span><br><span class="line">  <span class="comment">// 只拷贝对象</span></span><br><span class="line">  <span class="keyword">if</span> (!object || <span class="keyword">typeof</span> object !== <span class="string">&quot;object&quot;</span>) <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 根据 object 的类型判断是新建一个数组还是对象</span></span><br><span class="line">  <span class="keyword">let</span> newObject = <span class="title class_">Array</span>.<span class="title function_">isArray</span>(object) ? [] : &#123;&#125;;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 遍历 object，并且判断是 object 的属性才拷贝</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> key <span class="keyword">in</span> object) &#123;</span><br><span class="line">    <span class="keyword">if</span> (object.<span class="title function_">hasOwnProperty</span>(key)) &#123;</span><br><span class="line">      newObject[key] = object[key];</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> newObject;</span><br><span class="line">&#125;<span class="comment">// 浅拷贝的实现;</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">shallowCopy</span>(<span class="params">object</span>) &#123;</span><br><span class="line">  <span class="comment">// 只拷贝对象</span></span><br><span class="line">  <span class="keyword">if</span> (!object || <span class="keyword">typeof</span> object !== <span class="string">&quot;object&quot;</span>) <span class="keyword">return</span>;</span><br><span class="line">  <span class="comment">// 根据 object 的类型判断是新建一个数组还是对象</span></span><br><span class="line">  <span class="keyword">let</span> newObject = <span class="title class_">Array</span>.<span class="title function_">isArray</span>(object) ? [] : &#123;&#125;;</span><br><span class="line">  <span class="comment">// 遍历 object，并且判断是 object 的属性才拷贝</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> key <span class="keyword">in</span> object) &#123;</span><br><span class="line">    <span class="keyword">if</span> (object.<span class="title function_">hasOwnProperty</span>(key)) &#123;</span><br><span class="line">      newObject[key] = object[key];</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> newObject;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="18-实现深拷贝"><a href="#18-实现深拷贝" class="headerlink" title="18. 实现深拷贝"></a>18. 实现深拷贝</h3><ul>
<li><strong>浅拷贝：</strong> 浅拷贝指的是将一个对象的属性值复制到另一个对象，如果有的属性的值为引用类型的话，那么会将这个引用的地址复制给对象，因此两个对象会有同一个引用类型的引用。浅拷贝可以使用  Object.assign 和展开运算符来实现。</li>
<li><strong>深拷贝：</strong> 深拷贝相对浅拷贝而言，如果遇到属性值为引用类型的时候，它新建一个引用类型并将对应的值复制给它，因此对象获得的一个新的引用类型而不是一个原有类型的引用。深拷贝对于一些对象可以使用 JSON 的两个函数来实现，但是由于 JSON 的对象格式比 js 的对象格式更加严格，所以如果属性值里边出现函数或者 Symbol 类型的值时，会转换失败</li>
</ul>
<h4 id="（1）JSON-stringify"><a href="#（1）JSON-stringify" class="headerlink" title="（1）JSON.stringify()"></a>（1）JSON.stringify()</h4><ul>
<li><code>JSON.parse(JSON.stringify(obj))</code>是目前比较常用的深拷贝方法之一，它的原理就是利用<code>JSON.stringify</code> 将<code>js</code>对象序列化（JSON字符串），再使用<code>JSON.parse</code>来反序列化(还原)<code>js</code>对象。</li>
<li>这个方法可以简单粗暴的实现深拷贝，但是还存在问题，拷贝的对象中如果有函数，undefined，symbol，当使用过<code>JSON.stringify()</code>进行处理之后，都会消失。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> obj1 = &#123;  <span class="attr">a</span>: <span class="number">0</span>,</span><br><span class="line">              <span class="attr">b</span>: &#123;</span><br><span class="line">                 <span class="attr">c</span>: <span class="number">0</span></span><br><span class="line">                 &#125;</span><br><span class="line">            &#125;;</span><br><span class="line"><span class="keyword">let</span> obj2 = <span class="title class_">JSON</span>.<span class="title function_">parse</span>(<span class="title class_">JSON</span>.<span class="title function_">stringify</span>(obj1));</span><br><span class="line">obj1.<span class="property">a</span> = <span class="number">1</span>;</span><br><span class="line">obj1.<span class="property">b</span>.<span class="property">c</span> = <span class="number">1</span>;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(obj1); <span class="comment">// &#123;a: 1, b: &#123;c: 1&#125;&#125;</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(obj2); <span class="comment">// &#123;a: 0, b: &#123;c: 0&#125;&#125;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="（2）函数库lodash的-cloneDeep方法"><a href="#（2）函数库lodash的-cloneDeep方法" class="headerlink" title="（2）函数库lodash的_.cloneDeep方法"></a>（2）函数库lodash的_.cloneDeep方法</h4><p>该函数库也有提供_.cloneDeep用来做 Deep Copy</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> _ = <span class="built_in">require</span>(<span class="string">&#x27;lodash&#x27;</span>);</span><br><span class="line"><span class="keyword">var</span> obj1 = &#123;</span><br><span class="line">    <span class="attr">a</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">b</span>: &#123; <span class="attr">f</span>: &#123; <span class="attr">g</span>: <span class="number">1</span> &#125; &#125;,</span><br><span class="line">    <span class="attr">c</span>: [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">var</span> obj2 = _.<span class="title function_">cloneDeep</span>(obj1);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(obj1.<span class="property">b</span>.<span class="property">f</span> === obj2.<span class="property">b</span>.<span class="property">f</span>);<span class="comment">// false</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="（3）手写实现深拷贝函数"><a href="#（3）手写实现深拷贝函数" class="headerlink" title="（3）手写实现深拷贝函数"></a>（3）手写实现深拷贝函数</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 深拷贝的实现</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">deepCopy</span>(<span class="params">object</span>) &#123;</span><br><span class="line">  <span class="keyword">if</span> (!object || <span class="keyword">typeof</span> object !== <span class="string">&quot;object&quot;</span>) <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">let</span> newObject = <span class="title class_">Array</span>.<span class="title function_">isArray</span>(object) ? [] : &#123;&#125;;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> key <span class="keyword">in</span> object) &#123;</span><br><span class="line">    <span class="keyword">if</span> (object.<span class="title function_">hasOwnProperty</span>(key)) &#123;</span><br><span class="line">      newObject[key] =</span><br><span class="line">        <span class="keyword">typeof</span> object[key] === <span class="string">&quot;object&quot;</span> ? <span class="title function_">deepCopy</span>(object[key]) : object[key];</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> newObject;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="二、数据处理"><a href="#二、数据处理" class="headerlink" title="二、数据处理"></a>二、数据处理</h2><h3 id="1-实现日期格式化函数"><a href="#1-实现日期格式化函数" class="headerlink" title="1. 实现日期格式化函数"></a>1. 实现日期格式化函数</h3><p>输入：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">dateFormat</span>(<span class="keyword">new</span> <span class="title class_">Date</span>(<span class="string">&#x27;2020-12-01&#x27;</span>), <span class="string">&#x27;yyyy/MM/dd&#x27;</span>) <span class="comment">// 2020/12/01</span></span><br><span class="line"><span class="title function_">dateFormat</span>(<span class="keyword">new</span> <span class="title class_">Date</span>(<span class="string">&#x27;2020-04-01&#x27;</span>), <span class="string">&#x27;yyyy/MM/dd&#x27;</span>) <span class="comment">// 2020/04/01</span></span><br><span class="line"><span class="title function_">dateFormat</span>(<span class="keyword">new</span> <span class="title class_">Date</span>(<span class="string">&#x27;2020-04-01&#x27;</span>), <span class="string">&#x27;yyyy年MM月dd日&#x27;</span>) <span class="comment">// 2020年04月01日</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">dateFormat</span> = (<span class="params">dateInput, format</span>)=&gt;&#123;</span><br><span class="line">    <span class="keyword">var</span> day = dateInput.<span class="title function_">getDate</span>() </span><br><span class="line">    <span class="keyword">var</span> month = dateInput.<span class="title function_">getMonth</span>() + <span class="number">1</span>  </span><br><span class="line">    <span class="keyword">var</span> year = dateInput.<span class="title function_">getFullYear</span>()   </span><br><span class="line">    format = format.<span class="title function_">replace</span>(<span class="regexp">/yyyy/</span>, year)</span><br><span class="line">    format = format.<span class="title function_">replace</span>(<span class="regexp">/MM/</span>,month)</span><br><span class="line">    format = format.<span class="title function_">replace</span>(<span class="regexp">/dd/</span>,day)</span><br><span class="line">    <span class="keyword">return</span> format</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="2-交换a-b的值，不能用临时变量"><a href="#2-交换a-b的值，不能用临时变量" class="headerlink" title="2. 交换a,b的值，不能用临时变量"></a>2. 交换a,b的值，不能用临时变量</h3><p>巧妙的利用两个数的和、差：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">a = a + b</span><br><span class="line">b = a - b</span><br><span class="line">a = a - b</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="3-实现数组的乱序输出"><a href="#3-实现数组的乱序输出" class="headerlink" title="3. 实现数组的乱序输出"></a>3. 实现数组的乱序输出</h3><p>主要的实现思路就是：</p>
<ul>
<li>取出数组的第一个元素，随机产生一个索引值，将该第一个元素和这个索引对应的元素进行交换。</li>
<li>第二次取出数据数组第二个元素，随机产生一个除了索引为1的之外的索引值，并将第二个元素与该索引值对应的元素进行交换</li>
<li>按照上面的规律执行，直到遍历完成</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>];</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; arr.<span class="property">length</span>; i++) &#123;</span><br><span class="line">  <span class="keyword">const</span> randomIndex = <span class="title class_">Math</span>.<span class="title function_">round</span>(<span class="title class_">Math</span>.<span class="title function_">random</span>() * (arr.<span class="property">length</span> - <span class="number">1</span> - i)) + i;</span><br><span class="line">  [arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]];</span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(arr)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>还有一方法就是倒序遍历：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>];</span><br><span class="line"><span class="keyword">let</span> length = arr.<span class="property">length</span>,</span><br><span class="line">    randomIndex,</span><br><span class="line">    temp;</span><br><span class="line">  <span class="keyword">while</span> (length) &#123;</span><br><span class="line">    randomIndex = <span class="title class_">Math</span>.<span class="title function_">floor</span>(<span class="title class_">Math</span>.<span class="title function_">random</span>() * length--);</span><br><span class="line">    temp = arr[length];</span><br><span class="line">    arr[length] = arr[randomIndex];</span><br><span class="line">    arr[randomIndex] = temp;</span><br><span class="line">  &#125;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(arr)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="4-实现数组元素求和"><a href="#4-实现数组元素求和" class="headerlink" title="4. 实现数组元素求和"></a>4. 实现数组元素求和</h3><ul>
<li>arr&#x3D;[1,2,3,4,5,6,7,8,9,10]，求和</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>]</span><br><span class="line"><span class="keyword">let</span> sum = arr.<span class="title function_">reduce</span>( <span class="function">(<span class="params">total,i</span>) =&gt;</span> total += i,<span class="number">0</span>);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(sum);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<ul>
<li>arr&#x3D;[1,2,3,[[4,5],6],7,8,9]，求和</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> = arr=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,[[<span class="number">4</span>,<span class="number">5</span>],<span class="number">6</span>],<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>]</span><br><span class="line"><span class="keyword">let</span> arr= arr.<span class="title function_">toString</span>().<span class="title function_">split</span>(<span class="string">&#x27;,&#x27;</span>).<span class="title function_">reduce</span>( <span class="function">(<span class="params">total,i</span>) =&gt;</span> total += <span class="title class_">Number</span>(i),<span class="number">0</span>);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(arr);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>递归实现：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>] </span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">add</span>(<span class="params">arr</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (arr.<span class="property">length</span> == <span class="number">1</span>) <span class="keyword">return</span> arr[<span class="number">0</span>] </span><br><span class="line">    <span class="keyword">return</span> arr[<span class="number">0</span>] + <span class="title function_">add</span>(arr.<span class="title function_">slice</span>(<span class="number">1</span>)) </span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">add</span>(arr)) <span class="comment">// 21</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="5-实现数组的扁平化"><a href="#5-实现数组的扁平化" class="headerlink" title="5. 实现数组的扁平化"></a>5. 实现数组的扁平化</h3><p><strong>（1）递归实现</strong></p>
<p>普通的递归思路很容易理解，就是通过循环递归的方式，一项一项地去遍历，如果每一项还是一个数组，那么就继续往下遍历，利用递归程序的方法，来实现数组的每一项的连接：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>, [<span class="number">2</span>, [<span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>]]];</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">flatten</span>(<span class="params">arr</span>) &#123;</span><br><span class="line">  <span class="keyword">let</span> result = [];</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span>(<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; arr.<span class="property">length</span>; i++) &#123;</span><br><span class="line">    <span class="keyword">if</span>(<span class="title class_">Array</span>.<span class="title function_">isArray</span>(arr[i])) &#123;</span><br><span class="line">      result = result.<span class="title function_">concat</span>(<span class="title function_">flatten</span>(arr[i]));</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      result.<span class="title function_">push</span>(arr[i]);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">flatten</span>(arr);  <span class="comment">//  [1, 2, 3, 4，5]</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><strong>（2）reduce 函数迭代</strong></p>
<p>从上面普通的递归函数中可以看出，其实就是对数组的每一项进行处理，那么其实也可以用reduce 来实现数组的拼接，从而简化第一种方法的代码，改造后的代码如下所示：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>, [<span class="number">2</span>, [<span class="number">3</span>, <span class="number">4</span>]]];</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">flatten</span>(<span class="params">arr</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> arr.<span class="title function_">reduce</span>(<span class="keyword">function</span>(<span class="params">prev, next</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> prev.<span class="title function_">concat</span>(<span class="title class_">Array</span>.<span class="title function_">isArray</span>(next) ? <span class="title function_">flatten</span>(next) : next)</span><br><span class="line">    &#125;, [])</span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">flatten</span>(arr));<span class="comment">//  [1, 2, 3, 4，5]</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><strong>（3）扩展运算符实现</strong></p>
<p>这个方法的实现，采用了扩展运算符和 some 的方法，两者共同使用，达到数组扁平化的目的：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>, [<span class="number">2</span>, [<span class="number">3</span>, <span class="number">4</span>]]];</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">flatten</span>(<span class="params">arr</span>) &#123;</span><br><span class="line">    <span class="keyword">while</span> (arr.<span class="title function_">some</span>(<span class="function"><span class="params">item</span> =&gt;</span> <span class="title class_">Array</span>.<span class="title function_">isArray</span>(item))) &#123;</span><br><span class="line">        arr = [].<span class="title function_">concat</span>(...arr);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> arr;</span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">flatten</span>(arr)); <span class="comment">//  [1, 2, 3, 4，5]</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><strong>（4）split 和 toString</strong></p>
<p>可以通过 split 和 toString 两个方法来共同实现数组扁平化，由于数组会默认带一个 toString 的方法，所以可以把数组直接转换成逗号分隔的字符串，然后再用 split 方法把字符串重新转换为数组，如下面的代码所示：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>, [<span class="number">2</span>, [<span class="number">3</span>, <span class="number">4</span>]]];</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">flatten</span>(<span class="params">arr</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> arr.<span class="title function_">toString</span>().<span class="title function_">split</span>(<span class="string">&#x27;,&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">flatten</span>(arr)); <span class="comment">//  [1, 2, 3, 4，5]</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>通过这两个方法可以将多维数组直接转换成逗号连接的字符串，然后再重新分隔成数组。</p>
<p><strong>（5）ES6 中的 flat</strong></p>
<p>我们还可以直接调用 ES6 中的 flat 方法来实现数组扁平化。flat 方法的语法：<code>arr.flat([depth])</code></p>
<p>其中 depth 是 flat 的参数，depth 是可以传递数组的展开深度（默认不填、数值是 1），即展开一层数组。如果层数不确定，参数可以传进 Infinity，代表不论多少层都要展开：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>, [<span class="number">2</span>, [<span class="number">3</span>, <span class="number">4</span>]]];</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">flatten</span>(<span class="params">arr</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> arr.<span class="title function_">flat</span>(<span class="title class_">Infinity</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">flatten</span>(arr)); <span class="comment">//  [1, 2, 3, 4，5]</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>可以看出，一个嵌套了两层的数组，通过将 flat 方法的参数设置为 Infinity，达到了我们预期的效果。其实同样也可以设置成 2，也能实现这样的效果。在编程过程中，如果数组的嵌套层数不确定，最好直接使用 Infinity，可以达到扁平化。 <strong>（6）正则和 JSON 方法</strong> 在第4种方法中已经使用 toString 方法，其中仍然采用了将 JSON.stringify 的方法先转换为字符串，然后通过正则表达式过滤掉字符串中的数组的方括号，最后再利用 JSON.parse 把它转换成数组：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>, [<span class="number">2</span>, [<span class="number">3</span>, [<span class="number">4</span>, <span class="number">5</span>]]], <span class="number">6</span>];</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">flatten</span>(<span class="params">arr</span>) &#123;</span><br><span class="line">  <span class="keyword">let</span> str = <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(arr);</span><br><span class="line">  str = str.<span class="title function_">replace</span>(<span class="regexp">/(\[|\])/g</span>, <span class="string">&#x27;&#x27;</span>);</span><br><span class="line">  str = <span class="string">&#x27;[&#x27;</span> + str + <span class="string">&#x27;]&#x27;</span>;</span><br><span class="line">  <span class="keyword">return</span> <span class="title class_">JSON</span>.<span class="title function_">parse</span>(str); </span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">flatten</span>(arr)); <span class="comment">//  [1, 2, 3, 4，5]</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="6-实现数组去重"><a href="#6-实现数组去重" class="headerlink" title="6. 实现数组去重"></a>6. 实现数组去重</h3><p>给定某无序数组，要求去除数组中的重复数字并且返回新的无重复数组。</p>
<p>ES6方法（使用数据结构集合）：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> array = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">1</span>, <span class="number">5</span>, <span class="number">9</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">8</span>];</span><br><span class="line"></span><br><span class="line"><span class="title class_">Array</span>.<span class="title function_">from</span>(<span class="keyword">new</span> <span class="title class_">Set</span>(array)); <span class="comment">// [1, 2, 3, 5, 9, 8]</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>ES5方法：使用map存储不重复的数字</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> array = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">1</span>, <span class="number">5</span>, <span class="number">9</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">8</span>];</span><br><span class="line"></span><br><span class="line"><span class="title function_">uniqueArray</span>(array); <span class="comment">// [1, 2, 3, 5, 9, 8]</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">uniqueArray</span>(<span class="params">array</span>) &#123;</span><br><span class="line">  <span class="keyword">let</span> map = &#123;&#125;;</span><br><span class="line">  <span class="keyword">let</span> res = [];</span><br><span class="line">  <span class="keyword">for</span>(<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; array.<span class="property">length</span>; i++) &#123;</span><br><span class="line">    <span class="keyword">if</span>(!map.<span class="title function_">hasOwnProperty</span>([array[i]])) &#123;</span><br><span class="line">      map[array[i]] = <span class="number">1</span>;</span><br><span class="line">      res.<span class="title function_">push</span>(array[i]);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="7-实现数组的flat方法"><a href="#7-实现数组的flat方法" class="headerlink" title="7. 实现数组的flat方法"></a>7. 实现数组的flat方法</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">_flat</span>(<span class="params">arr, depth</span>) &#123;</span><br><span class="line">  <span class="keyword">if</span>(!<span class="title class_">Array</span>.<span class="title function_">isArray</span>(arr) || depth &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> arr;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> arr.<span class="title function_">reduce</span>(<span class="function">(<span class="params">prev, cur</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="title class_">Array</span>.<span class="title function_">isArray</span>(cur)) &#123;</span><br><span class="line">      <span class="keyword">return</span> prev.<span class="title function_">concat</span>(<span class="title function_">_flat</span>(cur, depth - <span class="number">1</span>))</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> prev.<span class="title function_">concat</span>(cur);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;, []);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="8-实现数组的push方法"><a href="#8-实现数组的push方法" class="headerlink" title="8. 实现数组的push方法"></a>8. 实现数组的push方法</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [];</span><br><span class="line"><span class="title class_">Array</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">push</span> = <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">	<span class="keyword">for</span>( <span class="keyword">let</span> i = <span class="number">0</span> ; i &lt; <span class="variable language_">arguments</span>.<span class="property">length</span> ; i++)&#123;</span><br><span class="line">		<span class="variable language_">this</span>[<span class="variable language_">this</span>.<span class="property">length</span>] = <span class="variable language_">arguments</span>[i] ;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">length</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="9-实现数组的filter方法"><a href="#9-实现数组的filter方法" class="headerlink" title="9. 实现数组的filter方法"></a>9. 实现数组的filter方法</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">Array</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">_filter</span> = <span class="keyword">function</span>(<span class="params">fn</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> fn !== <span class="string">&quot;function&quot;</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="title class_">Error</span>(<span class="string">&#x27;参数必须是一个函数&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> res = [];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>, len = <span class="variable language_">this</span>.<span class="property">length</span>; i &lt; len; i++) &#123;</span><br><span class="line">        <span class="title function_">fn</span>(<span class="variable language_">this</span>[i]) &amp;&amp; res.<span class="title function_">push</span>(<span class="variable language_">this</span>[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="10-实现数组的map方法"><a href="#10-实现数组的map方法" class="headerlink" title="10. 实现数组的map方法"></a>10. 实现数组的map方法</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">Array</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">_map</span> = <span class="keyword">function</span>(<span class="params">fn</span>) &#123;</span><br><span class="line">   <span class="keyword">if</span> (<span class="keyword">typeof</span> fn !== <span class="string">&quot;function&quot;</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="title class_">Error</span>(<span class="string">&#x27;参数必须是一个函数&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> res = [];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>, len = <span class="variable language_">this</span>.<span class="property">length</span>; i &lt; len; i++) &#123;</span><br><span class="line">        res.<span class="title function_">push</span>(<span class="title function_">fn</span>(<span class="variable language_">this</span>[i]));</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="11-实现字符串的repeat方法"><a href="#11-实现字符串的repeat方法" class="headerlink" title="11. 实现字符串的repeat方法"></a>11. 实现字符串的repeat方法</h3><p>输入字符串s，以及其重复的次数，输出重复的结果，例如输入abc，2，输出abcabc。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">repeat</span>(<span class="params">s, n</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> (<span class="keyword">new</span> <span class="title class_">Array</span>(n + <span class="number">1</span>)).<span class="title function_">join</span>(s);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>递归：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">repeat</span>(<span class="params">s, n</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> (n &gt; <span class="number">0</span>) ? s.<span class="title function_">concat</span>(<span class="title function_">repeat</span>(s, --n)) : <span class="string">&quot;&quot;</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="12-实现字符串翻转"><a href="#12-实现字符串翻转" class="headerlink" title="12. 实现字符串翻转"></a>12. 实现字符串翻转</h3><p>在字符串的原型链上添加一个方法，实现字符串翻转：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">String</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">_reverse</span> = <span class="keyword">function</span>(<span class="params">a</span>)&#123;</span><br><span class="line">    <span class="keyword">return</span> a.<span class="title function_">split</span>(<span class="string">&quot;&quot;</span>).<span class="title function_">reverse</span>().<span class="title function_">join</span>(<span class="string">&quot;&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj = <span class="keyword">new</span> <span class="title class_">String</span>();</span><br><span class="line"><span class="keyword">var</span> res = obj.<span class="property">_reverse</span> (<span class="string">&#x27;hello&#x27;</span>);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(res);    <span class="comment">// olleh</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>需要注意的是，必须通过实例化对象之后再去调用定义的方法，不然找不到该方法。</p>
<h3 id="13-将数字每千分位用逗号隔开"><a href="#13-将数字每千分位用逗号隔开" class="headerlink" title="13. 将数字每千分位用逗号隔开"></a>13. 将数字每千分位用逗号隔开</h3><p><strong>数字有小数版本：</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="title function_">format</span> = n =&gt; &#123;</span><br><span class="line">    <span class="keyword">let</span> num = n.<span class="title function_">toString</span>() <span class="comment">// 转成字符串</span></span><br><span class="line">    <span class="keyword">let</span> decimals = <span class="string">&#x27;&#x27;</span></span><br><span class="line">        <span class="comment">// 判断是否有小数</span></span><br><span class="line">    num.<span class="title function_">indexOf</span>(<span class="string">&#x27;.&#x27;</span>) &gt; -<span class="number">1</span> ? decimals = num.<span class="title function_">split</span>(<span class="string">&#x27;.&#x27;</span>)[<span class="number">1</span>] : decimals</span><br><span class="line">    <span class="keyword">let</span> len = num.<span class="property">length</span></span><br><span class="line">    <span class="keyword">if</span> (len &lt;= <span class="number">3</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> num</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> temp = <span class="string">&#x27;&#x27;</span></span><br><span class="line">        <span class="keyword">let</span> remainder = len % <span class="number">3</span></span><br><span class="line">        decimals ? temp = <span class="string">&#x27;.&#x27;</span> + decimals : temp</span><br><span class="line">        <span class="keyword">if</span> (remainder &gt; <span class="number">0</span>) &#123; <span class="comment">// 不是3的整数倍</span></span><br><span class="line">            <span class="keyword">return</span> num.<span class="title function_">slice</span>(<span class="number">0</span>, remainder) + <span class="string">&#x27;,&#x27;</span> + num.<span class="title function_">slice</span>(remainder, len).<span class="title function_">match</span>(<span class="regexp">/\d&#123;3&#125;/g</span>).<span class="title function_">join</span>(<span class="string">&#x27;,&#x27;</span>) + temp</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123; <span class="comment">// 是3的整数倍</span></span><br><span class="line">            <span class="keyword">return</span> num.<span class="title function_">slice</span>(<span class="number">0</span>, len).<span class="title function_">match</span>(<span class="regexp">/\d&#123;3&#125;/g</span>).<span class="title function_">join</span>(<span class="string">&#x27;,&#x27;</span>) + temp </span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">format</span>(<span class="number">12323.33</span>)  <span class="comment">// &#x27;12,323.33&#x27;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><strong>数字无小数版本：</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="title function_">format</span> = n =&gt; &#123;</span><br><span class="line">    <span class="keyword">let</span> num = n.<span class="title function_">toString</span>() </span><br><span class="line">    <span class="keyword">let</span> len = num.<span class="property">length</span></span><br><span class="line">    <span class="keyword">if</span> (len &lt;= <span class="number">3</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> num</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> remainder = len % <span class="number">3</span></span><br><span class="line">        <span class="keyword">if</span> (remainder &gt; <span class="number">0</span>) &#123; <span class="comment">// 不是3的整数倍</span></span><br><span class="line">            <span class="keyword">return</span> num.<span class="title function_">slice</span>(<span class="number">0</span>, remainder) + <span class="string">&#x27;,&#x27;</span> + num.<span class="title function_">slice</span>(remainder, len).<span class="title function_">match</span>(<span class="regexp">/\d&#123;3&#125;/g</span>).<span class="title function_">join</span>(<span class="string">&#x27;,&#x27;</span>) </span><br><span class="line">        &#125; <span class="keyword">else</span> &#123; <span class="comment">// 是3的整数倍</span></span><br><span class="line">            <span class="keyword">return</span> num.<span class="title function_">slice</span>(<span class="number">0</span>, len).<span class="title function_">match</span>(<span class="regexp">/\d&#123;3&#125;/g</span>).<span class="title function_">join</span>(<span class="string">&#x27;,&#x27;</span>) </span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">format</span>(<span class="number">1232323</span>)  <span class="comment">// &#x27;1,232,323&#x27;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="14-实现非负大整数相加"><a href="#14-实现非负大整数相加" class="headerlink" title="14. 实现非负大整数相加"></a>14. 实现非负大整数相加</h3><p>JavaScript对数值有范围的限制，限制如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">Number</span>.<span class="property">MAX_VALUE</span> <span class="comment">// 1.7976931348623157e+308</span></span><br><span class="line"><span class="title class_">Number</span>.<span class="property">MAX_SAFE_INTEGER</span> <span class="comment">// 9007199254740991</span></span><br><span class="line"><span class="title class_">Number</span>.<span class="property">MIN_VALUE</span> <span class="comment">// 5e-324</span></span><br><span class="line"><span class="title class_">Number</span>.<span class="property">MIN_SAFE_INTEGER</span> <span class="comment">// -9007199254740991</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>如果想要对一个超大的整数(<code>&gt; Number.MAX_SAFE_INTEGER</code>)进行加法运算，但是又想输出一般形式，那么使用 + 是无法达到的，一旦数字超过 <code>Number.MAX_SAFE_INTEGER</code> 数字会被立即转换为科学计数法，并且数字精度相比以前将会有误差。</p>
<p>实现一个算法进行大数的相加：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">sumBigNumber</span>(<span class="params">a, b</span>) &#123;</span><br><span class="line">  <span class="keyword">let</span> res = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">  <span class="keyword">let</span> temp = <span class="number">0</span>;</span><br><span class="line">  </span><br><span class="line">  a = a.<span class="title function_">split</span>(<span class="string">&#x27;&#x27;</span>);</span><br><span class="line">  b = b.<span class="title function_">split</span>(<span class="string">&#x27;&#x27;</span>);</span><br><span class="line">  </span><br><span class="line">  <span class="keyword">while</span> (a.<span class="property">length</span> || b.<span class="property">length</span> || temp) &#123;</span><br><span class="line">    temp += ~~a.<span class="title function_">pop</span>() + ~~b.<span class="title function_">pop</span>();</span><br><span class="line">    res = (temp % <span class="number">10</span>) + res;</span><br><span class="line">    temp  = temp &gt; <span class="number">9</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> res.<span class="title function_">replace</span>(<span class="regexp">/^0+/</span>, <span class="string">&#x27;&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>其主要的思路如下：</p>
<ul>
<li>首先用字符串的方式来保存大数，这样数字在数学表示上就不会发生变化</li>
<li>初始化res，temp来保存中间的计算结果，并将两个字符串转化为数组，以便进行每一位的加法运算</li>
<li>将两个数组的对应的位进行相加，两个数相加的结果可能大于10，所以可能要仅为，对10进行取余操作，将结果保存在当前位</li>
<li>判断当前位是否大于9，也就是是否会进位，若是则将temp赋值为true，因为在加法运算中，true会自动隐式转化为1，以便于下一次相加</li>
<li>重复上述操作，直至计算结束</li>
</ul>
<h3 id="13-实现-add-1-2-3"><a href="#13-实现-add-1-2-3" class="headerlink" title="13. 实现 add(1)(2)(3)"></a>13. 实现 add(1)(2)(3)</h3><p>函数柯里化概念： 柯里化（Currying）是把接受多个参数的函数转变为接受一个单一参数的函数，并且返回接受余下的参数且返回结果的新函数的技术。</p>
<p>1）粗暴版</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">add</span> (a) &#123;</span><br><span class="line"><span class="keyword">return</span> <span class="keyword">function</span> (<span class="params">b</span>) &#123;</span><br><span class="line"> 	<span class="keyword">return</span> <span class="keyword">function</span> (<span class="params">c</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> a + b + c;</span><br><span class="line"> 	&#125;</span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">add</span>(<span class="number">1</span>)(<span class="number">2</span>)(<span class="number">3</span>)); <span class="comment">// 6</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>2）柯里化解决方案</p>
<ul>
<li>参数长度固定</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> add = <span class="keyword">function</span> (<span class="params">m</span>) &#123;</span><br><span class="line">  <span class="keyword">var</span> temp = <span class="keyword">function</span> (<span class="params">n</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="title function_">add</span>(m + n);</span><br><span class="line">  &#125;</span><br><span class="line">  temp.<span class="property">toString</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> m;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> temp;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">add</span>(<span class="number">3</span>)(<span class="number">4</span>)(<span class="number">5</span>)); <span class="comment">// 12</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">add</span>(<span class="number">3</span>)(<span class="number">6</span>)(<span class="number">9</span>)(<span class="number">25</span>)); <span class="comment">// 43</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>对于add(3)(4)(5)，其执行过程如下：</p>
<ol>
<li>先执行add(3)，此时m&#x3D;3，并且返回temp函数；</li>
<li>执行temp(4)，这个函数内执行add(m+n)，n是此次传进来的数值4，m值还是上一步中的3，所以add(m+n)&#x3D;add(3+4)&#x3D;add(7)，此时m&#x3D;7，并且返回temp函数</li>
<li>执行temp(5)，这个函数内执行add(m+n)，n是此次传进来的数值5，m值还是上一步中的7，所以add(m+n)&#x3D;add(7+5)&#x3D;add(12)，此时m&#x3D;12，并且返回temp函数</li>
<li>由于后面没有传入参数，等于返回的temp函数不被执行而是打印，了解JS的朋友都知道对象的toString是修改对象转换字符串的方法，因此代码中temp函数的toString函数return m值，而m值是最后一步执行函数时的值m&#x3D;12，所以返回值是12。</li>
</ol>
<ul>
<li>参数长度不固定</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">add</span> (...args) &#123;</span><br><span class="line">    <span class="comment">//求和</span></span><br><span class="line">    <span class="keyword">return</span> args.<span class="title function_">reduce</span>(<span class="function">(<span class="params">a, b</span>) =&gt;</span> a + b)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">currying</span> (fn) &#123;</span><br><span class="line">    <span class="keyword">let</span> args = []</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">function</span> <span class="title function_">temp</span> (...newArgs) &#123;</span><br><span class="line">        <span class="keyword">if</span> (newArgs.<span class="property">length</span>) &#123;</span><br><span class="line">            args = [</span><br><span class="line">                ...args,</span><br><span class="line">                ...newArgs</span><br><span class="line">            ]</span><br><span class="line">            <span class="keyword">return</span> temp</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">let</span> val = fn.<span class="title function_">apply</span>(<span class="variable language_">this</span>, args)</span><br><span class="line">            args = [] <span class="comment">//保证再次调用时清空</span></span><br><span class="line">            <span class="keyword">return</span> val</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> addCurry = <span class="title function_">currying</span>(add)</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">addCurry</span>(<span class="number">1</span>)(<span class="number">2</span>)(<span class="number">3</span>)(<span class="number">4</span>, <span class="number">5</span>)())  <span class="comment">//15</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">addCurry</span>(<span class="number">1</span>)(<span class="number">2</span>)(<span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>)())  <span class="comment">//15</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">addCurry</span>(<span class="number">1</span>)(<span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>)())  <span class="comment">//15</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="14-实现类数组转化为数组"><a href="#14-实现类数组转化为数组" class="headerlink" title="14. 实现类数组转化为数组"></a>14. 实现类数组转化为数组</h3><p>类数组转换为数组的方法有这样几种：</p>
<ul>
<li>通过 call 调用数组的 slice 方法来实现转换</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">Array</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">slice</span>.<span class="title function_">call</span>(arrayLike);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<ul>
<li>通过 call 调用数组的 splice 方法来实现转换</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">Array</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">splice</span>.<span class="title function_">call</span>(arrayLike, <span class="number">0</span>);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<ul>
<li>通过 apply 调用数组的 concat 方法来实现转换</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">Array</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">concat</span>.<span class="title function_">apply</span>([], arrayLike);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<ul>
<li>通过 Array.from 方法来实现转换</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">Array</span>.<span class="title function_">from</span>(arrayLike);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="15-使用-reduce-求和"><a href="#15-使用-reduce-求和" class="headerlink" title="15. 使用 reduce 求和"></a>15. 使用 reduce 求和</h3><p>arr &#x3D; [1,2,3,4,5,6,7,8,9,10]，求和</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>]</span><br><span class="line">arr.<span class="title function_">reduce</span>(<span class="function">(<span class="params">prev, cur</span>) =&gt;</span> &#123; <span class="keyword">return</span> prev + cur &#125;, <span class="number">0</span>)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>arr &#x3D; [1,2,3,[[4,5],6],7,8,9]，求和</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>]</span><br><span class="line">arr.<span class="title function_">flat</span>(<span class="title class_">Infinity</span>).<span class="title function_">reduce</span>(<span class="function">(<span class="params">prev, cur</span>) =&gt;</span> &#123; <span class="keyword">return</span> prev + cur &#125;, <span class="number">0</span>)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>arr &#x3D; [{a:1, b:3}, {a:2, b:3, c:4}, {a:3}]，求和</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [&#123;<span class="attr">a</span>:<span class="number">9</span>, <span class="attr">b</span>:<span class="number">3</span>, <span class="attr">c</span>:<span class="number">4</span>&#125;, &#123;<span class="attr">a</span>:<span class="number">1</span>, <span class="attr">b</span>:<span class="number">3</span>&#125;, &#123;<span class="attr">a</span>:<span class="number">3</span>&#125;] </span><br><span class="line"></span><br><span class="line">arr.<span class="title function_">reduce</span>(<span class="function">(<span class="params">prev, cur</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> prev + cur[<span class="string">&quot;a&quot;</span>];</span><br><span class="line">&#125;, <span class="number">0</span>)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="16-将js对象转化为树形结构"><a href="#16-将js对象转化为树形结构" class="headerlink" title="16. 将js对象转化为树形结构"></a>16. 将js对象转化为树形结构</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 转换前：</span></span><br><span class="line">source = [&#123;</span><br><span class="line">            <span class="attr">id</span>: <span class="number">1</span>,</span><br><span class="line">            <span class="attr">pid</span>: <span class="number">0</span>,</span><br><span class="line">            <span class="attr">name</span>: <span class="string">&#x27;body&#x27;</span></span><br><span class="line">          &#125;, &#123;</span><br><span class="line">            <span class="attr">id</span>: <span class="number">2</span>,</span><br><span class="line">            <span class="attr">pid</span>: <span class="number">1</span>,</span><br><span class="line">            <span class="attr">name</span>: <span class="string">&#x27;title&#x27;</span></span><br><span class="line">          &#125;, &#123;</span><br><span class="line">            <span class="attr">id</span>: <span class="number">3</span>,</span><br><span class="line">            <span class="attr">pid</span>: <span class="number">2</span>,</span><br><span class="line">            <span class="attr">name</span>: <span class="string">&#x27;div&#x27;</span></span><br><span class="line">          &#125;]</span><br><span class="line"><span class="comment">// 转换为: </span></span><br><span class="line">tree = [&#123;</span><br><span class="line">          <span class="attr">id</span>: <span class="number">1</span>,</span><br><span class="line">          <span class="attr">pid</span>: <span class="number">0</span>,</span><br><span class="line">          <span class="attr">name</span>: <span class="string">&#x27;body&#x27;</span>,</span><br><span class="line">          <span class="attr">children</span>: [&#123;</span><br><span class="line">            <span class="attr">id</span>: <span class="number">2</span>,</span><br><span class="line">            <span class="attr">pid</span>: <span class="number">1</span>,</span><br><span class="line">            <span class="attr">name</span>: <span class="string">&#x27;title&#x27;</span>,</span><br><span class="line">            <span class="attr">children</span>: [&#123;</span><br><span class="line">              <span class="attr">id</span>: <span class="number">3</span>,</span><br><span class="line">              <span class="attr">pid</span>: <span class="number">1</span>,</span><br><span class="line">              <span class="attr">name</span>: <span class="string">&#x27;div&#x27;</span></span><br><span class="line">            &#125;]</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;]</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>代码实现：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">jsonToTree</span>(<span class="params">data</span>) &#123;</span><br><span class="line">  <span class="comment">// 初始化结果数组，并判断输入数据的格式</span></span><br><span class="line">  <span class="keyword">let</span> result = []</span><br><span class="line">  <span class="keyword">if</span>(!<span class="title class_">Array</span>.<span class="title function_">isArray</span>(data)) &#123;</span><br><span class="line">    <span class="keyword">return</span> result</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 使用map，将当前对象的id与当前对象对应存储起来</span></span><br><span class="line">  <span class="keyword">let</span> map = &#123;&#125;;</span><br><span class="line">  data.<span class="title function_">forEach</span>(<span class="function"><span class="params">item</span> =&gt;</span> &#123;</span><br><span class="line">    map[item.<span class="property">id</span>] = item;</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="comment">// </span></span><br><span class="line">  data.<span class="title function_">forEach</span>(<span class="function"><span class="params">item</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> parent = map[item.<span class="property">pid</span>];</span><br><span class="line">    <span class="keyword">if</span>(parent) &#123;</span><br><span class="line">      (parent.<span class="property">children</span> || (parent.<span class="property">children</span> = [])).<span class="title function_">push</span>(item);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      result.<span class="title function_">push</span>(item);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="17-使用ES5和ES6求函数参数的和"><a href="#17-使用ES5和ES6求函数参数的和" class="headerlink" title="17. 使用ES5和ES6求函数参数的和"></a>17. 使用ES5和ES6求函数参数的和</h3><p>ES5：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">sum</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> sum = <span class="number">0</span></span><br><span class="line">    <span class="title class_">Array</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">forEach</span>.<span class="title function_">call</span>(<span class="variable language_">arguments</span>, <span class="keyword">function</span>(<span class="params">item</span>) &#123;</span><br><span class="line">        sum += item * <span class="number">1</span></span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="keyword">return</span> sum</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>ES6：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">sum</span>(<span class="params">...nums</span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> sum = <span class="number">0</span></span><br><span class="line">    nums.<span class="title function_">forEach</span>(<span class="keyword">function</span>(<span class="params">item</span>) &#123;</span><br><span class="line">        sum += item * <span class="number">1</span></span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="keyword">return</span> sum</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="18-解析-URL-Params-为对象"><a href="#18-解析-URL-Params-为对象" class="headerlink" title="18. 解析 URL Params 为对象"></a>18. 解析 URL Params 为对象</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> url = <span class="string">&#x27;http://www.domain.com/?user=anonymous&amp;id=123&amp;id=456&amp;city=%E5%8C%97%E4%BA%AC&amp;enabled&#x27;</span>;</span><br><span class="line"><span class="title function_">parseParam</span>(url)</span><br><span class="line"><span class="comment">/* 结果</span></span><br><span class="line"><span class="comment">&#123; user: &#x27;anonymous&#x27;,</span></span><br><span class="line"><span class="comment">  id: [ 123, 456 ], // 重复出现的 key 要组装成数组，能被转成数字的就转成数字类型</span></span><br><span class="line"><span class="comment">  city: &#x27;北京&#x27;, // 中文需解码</span></span><br><span class="line"><span class="comment">  enabled: true, // 未指定值得 key 约定为 true</span></span><br><span class="line"><span class="comment">&#125;</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">parseParam</span>(<span class="params">url</span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> paramsStr = <span class="regexp">/.+\?(.+)$/</span>.<span class="title function_">exec</span>(url)[<span class="number">1</span>]; <span class="comment">// 将 ? 后面的字符串取出来</span></span><br><span class="line">  <span class="keyword">const</span> paramsArr = paramsStr.<span class="title function_">split</span>(<span class="string">&#x27;&amp;&#x27;</span>); <span class="comment">// 将字符串以 &amp; 分割后存到数组中</span></span><br><span class="line">  <span class="keyword">let</span> paramsObj = &#123;&#125;;</span><br><span class="line">  <span class="comment">// 将 params 存到对象中</span></span><br><span class="line">  paramsArr.<span class="title function_">forEach</span>(<span class="function"><span class="params">param</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="regexp">/=/</span>.<span class="title function_">test</span>(param)) &#123; <span class="comment">// 处理有 value 的参数</span></span><br><span class="line">      <span class="keyword">let</span> [key, val] = param.<span class="title function_">split</span>(<span class="string">&#x27;=&#x27;</span>); <span class="comment">// 分割 key 和 value</span></span><br><span class="line">      val = <span class="built_in">decodeURIComponent</span>(val); <span class="comment">// 解码</span></span><br><span class="line">      val = <span class="regexp">/^\d+$/</span>.<span class="title function_">test</span>(val) ? <span class="built_in">parseFloat</span>(val) : val; <span class="comment">// 判断是否转为数字</span></span><br><span class="line">      <span class="keyword">if</span> (paramsObj.<span class="title function_">hasOwnProperty</span>(key)) &#123; <span class="comment">// 如果对象有 key，则添加一个值</span></span><br><span class="line">        paramsObj[key] = [].<span class="title function_">concat</span>(paramsObj[key], val);</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123; <span class="comment">// 如果对象没有这个 key，创建 key 并设置值</span></span><br><span class="line">        paramsObj[key] = val;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123; <span class="comment">// 处理没有 value 的参数</span></span><br><span class="line">      paramsObj[param] = <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">  <span class="keyword">return</span> paramsObj;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="三、场景应用"><a href="#三、场景应用" class="headerlink" title="三、场景应用"></a>三、场景应用</h2><h3 id="1-循环打印红黄绿"><a href="#1-循环打印红黄绿" class="headerlink" title="1. 循环打印红黄绿"></a>1. 循环打印红黄绿</h3><p>下面来看一道比较典型的问题，通过这个问题来对比几种异步编程方法：<strong>红灯 3s 亮一次，绿灯 1s 亮一次，黄灯 2s 亮一次；如何让三个灯不断交替重复亮灯？</strong></p>
<p>三个亮灯函数：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">red</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;red&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">green</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;green&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">yellow</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;yellow&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>这道题复杂的地方在于<strong>需要“交替重复”亮灯</strong>，而不是“亮完一次”就结束了。</p>
<h4 id="（1）用-callback-实现"><a href="#（1）用-callback-实现" class="headerlink" title="（1）用 callback 实现"></a>（1）用 callback 实现</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">task</span> = (<span class="params">timer, light, callback</span>) =&gt; &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (light === <span class="string">&#x27;red&#x27;</span>) &#123;</span><br><span class="line">            <span class="title function_">red</span>()</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (light === <span class="string">&#x27;green&#x27;</span>) &#123;</span><br><span class="line">            <span class="title function_">green</span>()</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (light === <span class="string">&#x27;yellow&#x27;</span>) &#123;</span><br><span class="line">            <span class="title function_">yellow</span>()</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="title function_">callback</span>()</span><br><span class="line">    &#125;, timer)</span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">task</span>(<span class="number">3000</span>, <span class="string">&#x27;red&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="title function_">task</span>(<span class="number">2000</span>, <span class="string">&#x27;green&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="title function_">task</span>(<span class="number">1000</span>, <span class="string">&#x27;yellow&#x27;</span>, <span class="title class_">Function</span>.<span class="property"><span class="keyword">prototype</span></span>)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>这里存在一个 bug：代码只是完成了一次流程，执行后红黄绿灯分别只亮一次。该如何让它交替重复进行呢？</p>
<p>上面提到过递归，可以递归亮灯的一个周期：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">step</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">    <span class="title function_">task</span>(<span class="number">3000</span>, <span class="string">&#x27;red&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="title function_">task</span>(<span class="number">2000</span>, <span class="string">&#x27;green&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="title function_">task</span>(<span class="number">1000</span>, <span class="string">&#x27;yellow&#x27;</span>, step)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">step</span>()</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><strong>注意看黄灯亮的回调里又再次调用了 step 方法</strong> 以完成循环亮灯。</p>
<h4 id="（2）用-promise-实现"><a href="#（2）用-promise-实现" class="headerlink" title="（2）用 promise 实现"></a>（2）用 promise 实现</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">task</span> = (<span class="params">timer, light</span>) =&gt; </span><br><span class="line">    <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (light === <span class="string">&#x27;red&#x27;</span>) &#123;</span><br><span class="line">                <span class="title function_">red</span>()</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">if</span> (light === <span class="string">&#x27;green&#x27;</span>) &#123;</span><br><span class="line">                <span class="title function_">green</span>()</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">if</span> (light === <span class="string">&#x27;yellow&#x27;</span>) &#123;</span><br><span class="line">                <span class="title function_">yellow</span>()</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="title function_">resolve</span>()</span><br><span class="line">        &#125;, timer)</span><br><span class="line">    &#125;)</span><br><span class="line"><span class="keyword">const</span> <span class="title function_">step</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">    <span class="title function_">task</span>(<span class="number">3000</span>, <span class="string">&#x27;red&#x27;</span>)</span><br><span class="line">        .<span class="title function_">then</span>(<span class="function">() =&gt;</span> <span class="title function_">task</span>(<span class="number">2000</span>, <span class="string">&#x27;green&#x27;</span>))</span><br><span class="line">        .<span class="title function_">then</span>(<span class="function">() =&gt;</span> <span class="title function_">task</span>(<span class="number">2100</span>, <span class="string">&#x27;yellow&#x27;</span>))</span><br><span class="line">        .<span class="title function_">then</span>(step)</span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">step</span>()</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>这里将回调移除，在一次亮灯结束后，resolve 当前 promise，并依然使用递归进行。</p>
<h4 id="（3）用-async-x2F-await-实现"><a href="#（3）用-async-x2F-await-实现" class="headerlink" title="（3）用 async&#x2F;await 实现"></a>（3）用 async&#x2F;await 实现</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">taskRunner</span> =  <span class="keyword">async</span> (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">    <span class="keyword">await</span> <span class="title function_">task</span>(<span class="number">3000</span>, <span class="string">&#x27;red&#x27;</span>)</span><br><span class="line">    <span class="keyword">await</span> <span class="title function_">task</span>(<span class="number">2000</span>, <span class="string">&#x27;green&#x27;</span>)</span><br><span class="line">    <span class="keyword">await</span> <span class="title function_">task</span>(<span class="number">2100</span>, <span class="string">&#x27;yellow&#x27;</span>)</span><br><span class="line">    <span class="title function_">taskRunner</span>()</span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">taskRunner</span>()</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="2-实现每隔一秒打印-1-2-3-4"><a href="#2-实现每隔一秒打印-1-2-3-4" class="headerlink" title="2. 实现每隔一秒打印 1,2,3,4"></a>2. 实现每隔一秒打印 1,2,3,4</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用闭包实现</span></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">  (<span class="keyword">function</span>(<span class="params">i</span>) &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">      <span class="variable language_">console</span>.<span class="title function_">log</span>(i);</span><br><span class="line">    &#125;, i * <span class="number">1000</span>);</span><br><span class="line">  &#125;)(i);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 使用 let 块级作用域</span></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(i);</span><br><span class="line">  &#125;, i * <span class="number">1000</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="3-小孩报数问题"><a href="#3-小孩报数问题" class="headerlink" title="3. 小孩报数问题"></a>3. 小孩报数问题</h3><p>有30个小孩儿，编号从1-30，围成一圈依此报数，1、2、3 数到 3 的小孩儿退出这个圈， 然后下一个小孩 重新报数 1、2、3，问最后剩下的那个小孩儿的编号是多少?</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">childNum</span>(<span class="params">num, count</span>)&#123;</span><br><span class="line">    <span class="keyword">let</span> allplayer = [];    </span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; num; i++)&#123;</span><br><span class="line">        allplayer[i] = i + <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">let</span> exitCount = <span class="number">0</span>;    <span class="comment">// 离开人数</span></span><br><span class="line">    <span class="keyword">let</span> counter = <span class="number">0</span>;      <span class="comment">// 记录报数</span></span><br><span class="line">    <span class="keyword">let</span> curIndex = <span class="number">0</span>;     <span class="comment">// 当前下标</span></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">while</span>(exitCount &lt; num - <span class="number">1</span>)&#123;</span><br><span class="line">        <span class="keyword">if</span>(allplayer[curIndex] !== <span class="number">0</span>) counter++;    </span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span>(counter == count)&#123;</span><br><span class="line">            allplayer[curIndex] = <span class="number">0</span>;                 </span><br><span class="line">            counter = <span class="number">0</span>;</span><br><span class="line">            exitCount++;  </span><br><span class="line">        &#125;</span><br><span class="line">        curIndex++;</span><br><span class="line">        <span class="keyword">if</span>(curIndex == num)&#123;</span><br><span class="line">            curIndex = <span class="number">0</span>               </span><br><span class="line">        &#125;;           </span><br><span class="line">    &#125;    </span><br><span class="line">    <span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; num; i++)&#123;</span><br><span class="line">        <span class="keyword">if</span>(allplayer[i] !== <span class="number">0</span>)&#123;</span><br><span class="line">            <span class="keyword">return</span> allplayer[i]</span><br><span class="line">        &#125;      </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">childNum</span>(<span class="number">30</span>, <span class="number">3</span>)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="4-用Promise实现图片的异步加载"><a href="#4-用Promise实现图片的异步加载" class="headerlink" title="4. 用Promise实现图片的异步加载"></a>4. 用Promise实现图片的异步加载</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="title function_">imageAsync</span>=(<span class="params">url</span>)=&gt;&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>)=&gt;</span>&#123;</span><br><span class="line">                <span class="keyword">let</span> img = <span class="keyword">new</span> <span class="title class_">Image</span>();</span><br><span class="line">                img.<span class="property">src</span> = url;</span><br><span class="line">                img.οnlοad=<span class="function">()=&gt;</span>&#123;</span><br><span class="line">                    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">`图片请求成功，此处进行通用操作`</span>);</span><br><span class="line">                    <span class="title function_">resolve</span>(image);</span><br><span class="line">                &#125;</span><br><span class="line">                img.οnerrοr=<span class="function">(<span class="params">err</span>)=&gt;</span>&#123;</span><br><span class="line">                    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">`失败，此处进行失败的通用操作`</span>);</span><br><span class="line">                    <span class="title function_">reject</span>(err);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line"><span class="title function_">imageAsync</span>(<span class="string">&quot;url&quot;</span>).<span class="title function_">then</span>(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;加载成功&quot;</span>);</span><br><span class="line">&#125;).<span class="title function_">catch</span>(<span class="function">(<span class="params">error</span>)=&gt;</span>&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;加载失败&quot;</span>);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="5-实现发布-订阅模式"><a href="#5-实现发布-订阅模式" class="headerlink" title="5. 实现发布-订阅模式"></a>5. 实现发布-订阅模式</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">EventCenter</span>&#123;</span><br><span class="line">  <span class="comment">// 1. 定义事件容器，用来装事件数组</span></span><br><span class="line">	<span class="keyword">let</span> handlers = &#123;&#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 2. 添加事件方法，参数：事件名 事件方法</span></span><br><span class="line">  <span class="title function_">addEventListener</span>(<span class="params">type, handler</span>) &#123;</span><br><span class="line">    <span class="comment">// 创建新数组容器</span></span><br><span class="line">    <span class="keyword">if</span> (!<span class="variable language_">this</span>.<span class="property">handlers</span>[type]) &#123;</span><br><span class="line">      <span class="variable language_">this</span>.<span class="property">handlers</span>[type] = []</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 存入事件</span></span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">handlers</span>[type].<span class="title function_">push</span>(handler)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 3. 触发事件，参数：事件名 事件参数</span></span><br><span class="line">  <span class="title function_">dispatchEvent</span>(<span class="params">type, params</span>) &#123;</span><br><span class="line">    <span class="comment">// 若没有注册该事件则抛出错误</span></span><br><span class="line">    <span class="keyword">if</span> (!<span class="variable language_">this</span>.<span class="property">handlers</span>[type]) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&#x27;该事件未注册&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 触发事件</span></span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">handlers</span>[type].<span class="title function_">forEach</span>(<span class="function"><span class="params">handler</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="title function_">handler</span>(...params)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 4. 事件移除，参数：事件名 要删除事件，若无第二个参数则删除该事件的订阅和发布</span></span><br><span class="line">  <span class="title function_">removeEventListener</span>(<span class="params">type, handler</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (!<span class="variable language_">this</span>.<span class="property">handlers</span>[type]) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&#x27;事件无效&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (!handler) &#123;</span><br><span class="line">      <span class="comment">// 移除事件</span></span><br><span class="line">      <span class="keyword">delete</span> <span class="variable language_">this</span>.<span class="property">handlers</span>[type]</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="keyword">const</span> index = <span class="variable language_">this</span>.<span class="property">handlers</span>[type].<span class="title function_">findIndex</span>(<span class="function"><span class="params">el</span> =&gt;</span> el === handler)</span><br><span class="line">      <span class="keyword">if</span> (index === -<span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&#x27;无该绑定事件&#x27;</span>)</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 移除事件</span></span><br><span class="line">      <span class="variable language_">this</span>.<span class="property">handlers</span>[type].<span class="title function_">splice</span>(index, <span class="number">1</span>)</span><br><span class="line">      <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">handlers</span>[type].<span class="property">length</span> === <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">delete</span> <span class="variable language_">this</span>.<span class="property">handlers</span>[type]</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="6-查找文章中出现频率最高的单词"><a href="#6-查找文章中出现频率最高的单词" class="headerlink" title="6. 查找文章中出现频率最高的单词"></a>6. 查找文章中出现频率最高的单词</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">findMostWord</span>(<span class="params">article</span>) &#123;</span><br><span class="line">  <span class="comment">// 合法性判断</span></span><br><span class="line">  <span class="keyword">if</span> (!article) <span class="keyword">return</span>;</span><br><span class="line">  <span class="comment">// 参数处理</span></span><br><span class="line">  article = article.<span class="title function_">trim</span>().<span class="title function_">toLowerCase</span>();</span><br><span class="line">  <span class="keyword">let</span> wordList = article.<span class="title function_">match</span>(<span class="regexp">/[a-z]+/g</span>),</span><br><span class="line">    visited = [],</span><br><span class="line">    maxNum = <span class="number">0</span>,</span><br><span class="line">    maxWord = <span class="string">&quot;&quot;</span>;</span><br><span class="line">  article = <span class="string">&quot; &quot;</span> + wordList.<span class="title function_">join</span>(<span class="string">&quot;  &quot;</span>) + <span class="string">&quot; &quot;</span>;</span><br><span class="line">  <span class="comment">// 遍历判断单词出现次数</span></span><br><span class="line">  wordList.<span class="title function_">forEach</span>(<span class="keyword">function</span>(<span class="params">item</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (visited.<span class="title function_">indexOf</span>(item) &lt; <span class="number">0</span>) &#123;</span><br><span class="line">      <span class="comment">// 加入 visited </span></span><br><span class="line">      visited.<span class="title function_">push</span>(item);</span><br><span class="line">      <span class="keyword">let</span> word = <span class="keyword">new</span> <span class="title class_">RegExp</span>(<span class="string">&quot; &quot;</span> + item + <span class="string">&quot; &quot;</span>, <span class="string">&quot;g&quot;</span>),</span><br><span class="line">        num = article.<span class="title function_">match</span>(word).<span class="property">length</span>;</span><br><span class="line">      <span class="keyword">if</span> (num &gt; maxNum) &#123;</span><br><span class="line">        maxNum = num;</span><br><span class="line">        maxWord = item;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">return</span> maxWord + <span class="string">&quot;  &quot;</span> + maxNum;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="7-封装异步的fetch，使用async-await方式来使用"><a href="#7-封装异步的fetch，使用async-await方式来使用" class="headerlink" title="7. 封装异步的fetch，使用async await方式来使用"></a>7. 封装异步的fetch，使用async await方式来使用</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line">(<span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">    <span class="keyword">class</span> <span class="title class_">HttpRequestUtil</span> &#123;</span><br><span class="line">        <span class="keyword">async</span> <span class="title function_">get</span>(<span class="params">url</span>) &#123;</span><br><span class="line">            <span class="keyword">const</span> res = <span class="keyword">await</span> <span class="title function_">fetch</span>(url);</span><br><span class="line">            <span class="keyword">const</span> data = <span class="keyword">await</span> res.<span class="title function_">json</span>();</span><br><span class="line">            <span class="keyword">return</span> data;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">async</span> <span class="title function_">post</span>(<span class="params">url, data</span>) &#123;</span><br><span class="line">            <span class="keyword">const</span> res = <span class="keyword">await</span> <span class="title function_">fetch</span>(url, &#123;</span><br><span class="line">                <span class="attr">method</span>: <span class="string">&#x27;POST&#x27;</span>,</span><br><span class="line">                <span class="attr">headers</span>: &#123;</span><br><span class="line">                    <span class="string">&#x27;Content-Type&#x27;</span>: <span class="string">&#x27;application/json&#x27;</span></span><br><span class="line">                &#125;,</span><br><span class="line">                <span class="attr">body</span>: <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(data)</span><br><span class="line">            &#125;);</span><br><span class="line">            <span class="keyword">const</span> result = <span class="keyword">await</span> res.<span class="title function_">json</span>();</span><br><span class="line">            <span class="keyword">return</span> result;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">async</span> <span class="title function_">put</span>(<span class="params">url, data</span>) &#123;</span><br><span class="line">            <span class="keyword">const</span> res = <span class="keyword">await</span> <span class="title function_">fetch</span>(url, &#123;</span><br><span class="line">                <span class="attr">method</span>: <span class="string">&#x27;PUT&#x27;</span>,</span><br><span class="line">                <span class="attr">headers</span>: &#123;</span><br><span class="line">                    <span class="string">&#x27;Content-Type&#x27;</span>: <span class="string">&#x27;application/json&#x27;</span></span><br><span class="line">                &#125;,</span><br><span class="line">                <span class="attr">data</span>: <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(data)</span><br><span class="line">            &#125;);</span><br><span class="line">            <span class="keyword">const</span> result = <span class="keyword">await</span> res.<span class="title function_">json</span>();</span><br><span class="line">            <span class="keyword">return</span> result;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">async</span> <span class="title function_">delete</span>(<span class="params">url, data</span>) &#123;</span><br><span class="line">            <span class="keyword">const</span> res = <span class="keyword">await</span> <span class="title function_">fetch</span>(url, &#123;</span><br><span class="line">                <span class="attr">method</span>: <span class="string">&#x27;DELETE&#x27;</span>,</span><br><span class="line">                <span class="attr">headers</span>: &#123;</span><br><span class="line">                    <span class="string">&#x27;Content-Type&#x27;</span>: <span class="string">&#x27;application/json&#x27;</span></span><br><span class="line">                &#125;,</span><br><span class="line">                <span class="attr">data</span>: <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(data)</span><br><span class="line">            &#125;);</span><br><span class="line">            <span class="keyword">const</span> result = <span class="keyword">await</span> res.<span class="title function_">json</span>();</span><br><span class="line">            <span class="keyword">return</span> result;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> httpRequestUtil = <span class="keyword">new</span> <span class="title class_">HttpRequestUtil</span>();</span><br><span class="line">    <span class="keyword">const</span> res = <span class="keyword">await</span> httpRequestUtil.<span class="title function_">get</span>(<span class="string">&#x27;http://golderbrother.cn/&#x27;</span>);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">&#125;)();</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="8-实现prototype继承"><a href="#8-实现prototype继承" class="headerlink" title="8. 实现prototype继承"></a>8. 实现prototype继承</h3><p>所谓的原型链继承就是让新实例的原型等于父类的实例：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//父方法</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">SupperFunction</span>(<span class="params">flag1</span>)&#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">flag1</span> = flag1;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//子方法</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">SubFunction</span>(<span class="params">flag2</span>)&#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">flag2</span> = flag2;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//父实例</span></span><br><span class="line"><span class="keyword">var</span> superInstance = <span class="keyword">new</span> <span class="title class_">SupperFunction</span>(<span class="literal">true</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//子继承父</span></span><br><span class="line"><span class="title class_">SubFunction</span>.<span class="property"><span class="keyword">prototype</span></span> = superInstance;</span><br><span class="line"></span><br><span class="line"><span class="comment">//子实例</span></span><br><span class="line"><span class="keyword">var</span> subInstance = <span class="keyword">new</span> <span class="title class_">SubFunction</span>(<span class="literal">false</span>);</span><br><span class="line"><span class="comment">//子调用自己和父的属性</span></span><br><span class="line">subInstance.<span class="property">flag1</span>;   <span class="comment">// true</span></span><br><span class="line">subInstance.<span class="property">flag2</span>;   <span class="comment">// false</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="9-实现双向数据绑定"><a href="#9-实现双向数据绑定" class="headerlink" title="9. 实现双向数据绑定"></a>9. 实现双向数据绑定</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> obj = &#123;&#125;</span><br><span class="line"><span class="keyword">let</span> input = <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&#x27;input&#x27;</span>)</span><br><span class="line"><span class="keyword">let</span> span = <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&#x27;span&#x27;</span>)</span><br><span class="line"><span class="comment">// 数据劫持</span></span><br><span class="line"><span class="title class_">Object</span>.<span class="title function_">defineProperty</span>(obj, <span class="string">&#x27;text&#x27;</span>, &#123;</span><br><span class="line">  <span class="attr">configurable</span>: <span class="literal">true</span>,</span><br><span class="line">  <span class="attr">enumerable</span>: <span class="literal">true</span>,</span><br><span class="line">  <span class="title function_">get</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;获取数据了&#x27;</span>)</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="title function_">set</span>(<span class="params">newVal</span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;数据更新了&#x27;</span>)</span><br><span class="line">    input.<span class="property">value</span> = newVal</span><br><span class="line">    span.<span class="property">innerHTML</span> = newVal</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// 输入监听</span></span><br><span class="line">input.<span class="title function_">addEventListener</span>(<span class="string">&#x27;keyup&#x27;</span>, <span class="keyword">function</span>(<span class="params">e</span>) &#123;</span><br><span class="line">  obj.<span class="property">text</span> = e.<span class="property">target</span>.<span class="property">value</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="10-实现简单路由"><a href="#10-实现简单路由" class="headerlink" title="10. 实现简单路由"></a>10. 实现简单路由</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// hash路由</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Route</span>&#123;</span><br><span class="line">  <span class="title function_">constructor</span>(<span class="params"></span>)&#123;</span><br><span class="line">    <span class="comment">// 路由存储对象</span></span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">routes</span> = &#123;&#125;</span><br><span class="line">    <span class="comment">// 当前hash</span></span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">currentHash</span> = <span class="string">&#x27;&#x27;</span></span><br><span class="line">    <span class="comment">// 绑定this，避免监听时this指向改变</span></span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">freshRoute</span> = <span class="variable language_">this</span>.<span class="property">freshRoute</span>.<span class="title function_">bind</span>(<span class="variable language_">this</span>)</span><br><span class="line">    <span class="comment">// 监听</span></span><br><span class="line">    <span class="variable language_">window</span>.<span class="title function_">addEventListener</span>(<span class="string">&#x27;load&#x27;</span>, <span class="variable language_">this</span>.<span class="property">freshRoute</span>, <span class="literal">false</span>)</span><br><span class="line">    <span class="variable language_">window</span>.<span class="title function_">addEventListener</span>(<span class="string">&#x27;hashchange&#x27;</span>, <span class="variable language_">this</span>.<span class="property">freshRoute</span>, <span class="literal">false</span>)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 存储</span></span><br><span class="line">  storeRoute (path, cb) &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">routes</span>[path] = cb || <span class="keyword">function</span> (<span class="params"></span>) &#123;&#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 更新</span></span><br><span class="line">  freshRoute () &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">currentHash</span> = location.<span class="property">hash</span>.<span class="title function_">slice</span>(<span class="number">1</span>) || <span class="string">&#x27;/&#x27;</span></span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">routes</span>[<span class="variable language_">this</span>.<span class="property">currentHash</span>]()</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="11-实现斐波那契数列"><a href="#11-实现斐波那契数列" class="headerlink" title="11. 实现斐波那契数列"></a>11. 实现斐波那契数列</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 递归</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">fn</span> (n)&#123;</span><br><span class="line">    <span class="keyword">if</span>(n==<span class="number">0</span>) <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line">    <span class="keyword">if</span>(n==<span class="number">1</span>) <span class="keyword">return</span> <span class="number">1</span></span><br><span class="line">    <span class="keyword">return</span> <span class="title function_">fn</span>(n-<span class="number">2</span>)+<span class="title function_">fn</span>(n-<span class="number">1</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 优化</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">fibonacci2</span>(<span class="params">n</span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> arr = [<span class="number">1</span>, <span class="number">1</span>, <span class="number">2</span>];</span><br><span class="line">    <span class="keyword">const</span> arrLen = arr.<span class="property">length</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (n &lt;= arrLen) &#123;</span><br><span class="line">        <span class="keyword">return</span> arr[n];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = arrLen; i &lt; n; i++) &#123;</span><br><span class="line">        arr.<span class="title function_">push</span>(arr[i - <span class="number">1</span>] + arr[ i - <span class="number">2</span>]);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> arr[arr.<span class="property">length</span> - <span class="number">1</span>];</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 非递归</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">fn</span>(<span class="params">n</span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> pre1 = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">let</span> pre2 = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">let</span> current = <span class="number">2</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (n &lt;= <span class="number">2</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> current;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">2</span>; i &lt; n; i++) &#123;</span><br><span class="line">        pre1 = pre2;</span><br><span class="line">        pre2 = current;</span><br><span class="line">        current = pre1 + pre2;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> current;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="12-字符串出现的不重复最长长度"><a href="#12-字符串出现的不重复最长长度" class="headerlink" title="12. 字符串出现的不重复最长长度"></a>12. 字符串出现的不重复最长长度</h3><p>用一个滑动窗口装没有重复的字符，枚举字符记录最大值即可。用 map 维护字符的索引，遇到相同的字符，把左边界移动过去即可。挪动的过程中记录最大长度：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> lengthOfLongestSubstring = <span class="keyword">function</span> (<span class="params">s</span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> map = <span class="keyword">new</span> <span class="title class_">Map</span>();</span><br><span class="line">    <span class="keyword">let</span> i = -<span class="number">1</span></span><br><span class="line">    <span class="keyword">let</span> res = <span class="number">0</span></span><br><span class="line">    <span class="keyword">let</span> n = s.<span class="property">length</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> j = <span class="number">0</span>; j &lt; n; j++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (map.<span class="title function_">has</span>(s[j])) &#123;</span><br><span class="line">            i = <span class="title class_">Math</span>.<span class="title function_">max</span>(i, map.<span class="title function_">get</span>(s[j]))</span><br><span class="line">        &#125;</span><br><span class="line">        res = <span class="title class_">Math</span>.<span class="title function_">max</span>(res, j - i)</span><br><span class="line">        map.<span class="title function_">set</span>(s[j], j)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res</span><br><span class="line">&#125;;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="13-使用-setTimeout-实现-setInterval"><a href="#13-使用-setTimeout-实现-setInterval" class="headerlink" title="13. 使用 setTimeout 实现 setInterval"></a>13. 使用 setTimeout 实现 setInterval</h3><p>setInterval 的作用是每隔一段指定时间执行一个函数，但是这个执行不是真的到了时间立即执行，它真正的作用是每隔一段时间将事件加入事件队列中去，只有当当前的执行栈为空的时候，才能去从事件队列中取出事件执行。所以可能会出现这样的情况，就是当前执行栈执行的时间很长，导致事件队列里边积累多个定时器加入的事件，当执行栈结束的时候，这些事件会依次执行，因此就不能到间隔一段时间执行的效果。</p>
<p>针对 setInterval 的这个缺点，我们可以使用 setTimeout 递归调用来模拟 setInterval，这样我们就确保了只有一个事件结束了，我们才会触发下一个定时器事件，这样解决了 setInterval 的问题。</p>
<p>实现思路是使用递归函数，不断地去执行 setTimeout 从而达到 setInterval 的效果</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">mySetInterval</span>(<span class="params">fn, timeout</span>) &#123;</span><br><span class="line">  <span class="comment">// 控制器，控制定时器是否继续执行</span></span><br><span class="line">  <span class="keyword">var</span> timer = &#123;</span><br><span class="line">    <span class="attr">flag</span>: <span class="literal">true</span></span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="comment">// 设置递归函数，模拟定时器执行。</span></span><br><span class="line">  <span class="keyword">function</span> <span class="title function_">interval</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (timer.<span class="property">flag</span>) &#123;</span><br><span class="line">      <span class="title function_">fn</span>();</span><br><span class="line">      <span class="built_in">setTimeout</span>(interval, timeout);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 启动定时器</span></span><br><span class="line">  <span class="built_in">setTimeout</span>(interval, timeout);</span><br><span class="line">  <span class="comment">// 返回控制器</span></span><br><span class="line">  <span class="keyword">return</span> timer;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="14-实现-jsonp"><a href="#14-实现-jsonp" class="headerlink" title="14. 实现 jsonp"></a>14. 实现 jsonp</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 动态的加载js文件</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">addScript</span>(<span class="params">src</span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> script = <span class="variable language_">document</span>.<span class="title function_">createElement</span>(<span class="string">&#x27;script&#x27;</span>);</span><br><span class="line">  script.<span class="property">src</span> = src;</span><br><span class="line">  script.<span class="property">type</span> = <span class="string">&quot;text/javascript&quot;</span>;</span><br><span class="line">  <span class="variable language_">document</span>.<span class="property">body</span>.<span class="title function_">appendChild</span>(script);</span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">addScript</span>(<span class="string">&quot;http://xxx.xxx.com/xxx.js?callback=handleRes&quot;</span>);</span><br><span class="line"><span class="comment">// 设置一个全局的callback函数来接收回调结果</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">handleRes</span>(<span class="params">res</span>) &#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 接口返回的数据格式</span></span><br><span class="line"><span class="title function_">handleRes</span>(&#123;<span class="attr">a</span>: <span class="number">1</span>, <span class="attr">b</span>: <span class="number">2</span>&#125;);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="15-判断对象是否存在循环引用"><a href="#15-判断对象是否存在循环引用" class="headerlink" title="15. 判断对象是否存在循环引用"></a>15. 判断对象是否存在循环引用</h3><p>循环引用对象本来没有什么问题，但是序列化的时候就会发生问题，比如调用<code>JSON.stringify()</code>对该类对象进行序列化，就会报错: <code>Converting circular structure to JSON.</code></p>
<p>下面方法可以用来判断一个对象中是否已存在循环引用：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">isCycleObject</span> = (<span class="params">obj,parent</span>) =&gt; &#123;</span><br><span class="line">    <span class="keyword">const</span> parentArr = parent || [obj];</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">let</span> i <span class="keyword">in</span> obj) &#123;</span><br><span class="line">        <span class="keyword">if</span>(<span class="keyword">typeof</span> obj[i] === <span class="string">&#x27;object&#x27;</span>) &#123;</span><br><span class="line">            <span class="keyword">let</span> flag = <span class="literal">false</span>;</span><br><span class="line">            parentArr.<span class="title function_">forEach</span>(<span class="function">(<span class="params">pObj</span>) =&gt;</span> &#123;</span><br><span class="line">                <span class="keyword">if</span>(pObj === obj[i])&#123;</span><br><span class="line">                    flag = <span class="literal">true</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;)</span><br><span class="line">            <span class="keyword">if</span>(flag) <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">            flag = <span class="title function_">isCycleObject</span>(obj[i],[...parentArr,obj[i]]);</span><br><span class="line">            <span class="keyword">if</span>(flag) <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> a = <span class="number">1</span>;</span><br><span class="line"><span class="keyword">const</span> b = &#123;a&#125;;</span><br><span class="line"><span class="keyword">const</span> c = &#123;b&#125;;</span><br><span class="line"><span class="keyword">const</span> o = &#123;<span class="attr">d</span>:&#123;<span class="attr">a</span>:<span class="number">3</span>&#125;,c&#125;</span><br><span class="line">o.<span class="property">c</span>.<span class="property">b</span>.<span class="property">aa</span> = a;</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">isCycleObject</span>(o)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>查找有序二维数组的目标值：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> findNumberIn2DArray = <span class="keyword">function</span>(<span class="params">matrix, target</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (matrix == <span class="literal">null</span> || matrix.<span class="property">length</span> == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">let</span> row = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">let</span> column = matrix[<span class="number">0</span>].<span class="property">length</span> - <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">while</span> (row &lt; matrix.<span class="property">length</span> &amp;&amp; column &gt;= <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (matrix[row][column] == target) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (matrix[row][column] &gt; target) &#123;</span><br><span class="line">            column--;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            row++;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>二维数组斜向打印：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">printMatrix</span>(<span class="params">arr</span>)&#123;</span><br><span class="line">  <span class="keyword">let</span> m = arr.<span class="property">length</span>, n = arr[<span class="number">0</span>].<span class="property">length</span></span><br><span class="line">	<span class="keyword">let</span> res = []</span><br><span class="line">  </span><br><span class="line">  <span class="comment">// 左上角，从0 到 n - 1 列进行打印</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> k = <span class="number">0</span>; k &lt; n; k++) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>, j = k; i &lt; m &amp;&amp; j &gt;= <span class="number">0</span>; i++, j--) &#123;</span><br><span class="line">      res.<span class="title function_">push</span>(arr[i][j]);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 右下角，从1 到 n - 1 行进行打印</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> k = <span class="number">1</span>; k &lt; m; k++) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = k, j = n - <span class="number">1</span>; i &lt; m &amp;&amp; j &gt;= <span class="number">0</span>; i++, j--) &#123;</span><br><span class="line">      res.<span class="title function_">push</span>(arr[i][j]);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> res</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="https://szhihao.gitee.io">孙志豪</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="https://szhihao.gitee.io/2022/10/11/07-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/js%E6%89%8B%E5%86%99%E4%BB%A3%E7%A0%81%E9%9D%A2%E8%AF%95%E9%A2%98/">https://szhihao.gitee.io/2022/10/11/07-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/js%E6%89%8B%E5%86%99%E4%BB%A3%E7%A0%81%E9%9D%A2%E8%AF%95%E9%A2%98/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="/img/%E5%A4%A9%E7%A9%BA.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/10/11/14-%E5%89%8D%E7%AB%AF%E6%A1%86%E6%9E%B6%EF%BC%88Vue%E9%9D%A2%E8%AF%95%E9%A2%98%EF%BC%89/%E6%9C%80%E5%85%A8%E7%9A%84%20Vue%20%E9%9D%A2%E8%AF%95%E9%A2%98+%E8%AF%A6%E8%A7%A3%E7%AD%94%E6%A1%88/"><img class="prev-cover" src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">最全的 Vue 面试题+详解答案</div></div></a></div><div class="next-post pull-right"><a href="/2022/10/11/07-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/%E6%AD%BB%E7%A3%95%2036%20%E4%B8%AA%20JS%20%E6%89%8B%E5%86%99%E9%A2%98%EF%BC%88%E6%90%9E%E6%87%82%E5%90%8E%EF%BC%8C%E6%8F%90%E5%8D%87%E7%9C%9F%E7%9A%84%E5%A4%A7%EF%BC%89/"><img class="next-cover" src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">Next Post</div><div class="next_info">死磕 36 个 JS 手写题（搞懂后，提升真的大）</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="/img/%E5%A4%B4%E5%83%8F.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">孙志豪</div><div class="author-info__description">吾日三省吾身：为人谋而不忠乎？与朋友交而不信乎？传不习乎？</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">44</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">15</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/szhihao/szhihao"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/szhihao/szhihao" target="_blank" title="Gitee"><i class="fab fa-github"></i></a><a class="social-icon" href="https://blog.csdn.net/qq_54753561" target="_blank" title="CSDN"><i class="fa fa-book-open"></i></a><a class="social-icon" href="mailto:zhihaomail@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>Announcement</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E6%89%8B%E5%86%99-Object-create"><span class="toc-number">1.</span> <span class="toc-text">1. 手写 Object.create</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E6%89%8B%E5%86%99-instanceof-%E6%96%B9%E6%B3%95"><span class="toc-number">2.</span> <span class="toc-text">2. 手写 instanceof 方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E6%89%8B%E5%86%99-new-%E6%93%8D%E4%BD%9C%E7%AC%A6"><span class="toc-number">3.</span> <span class="toc-text">3. 手写 new 操作符</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E6%89%8B%E5%86%99-Promise"><span class="toc-number">4.</span> <span class="toc-text">4. 手写 Promise</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-%E6%89%8B%E5%86%99-Promise-then"><span class="toc-number">5.</span> <span class="toc-text">5. 手写 Promise.then</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-%E6%89%8B%E5%86%99-Promise-all"><span class="toc-number">6.</span> <span class="toc-text">6. 手写 Promise.all</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-%E6%89%8B%E5%86%99-Promise-race"><span class="toc-number">7.</span> <span class="toc-text">7. 手写 Promise.race</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-%E6%89%8B%E5%86%99%E9%98%B2%E6%8A%96%E5%87%BD%E6%95%B0"><span class="toc-number">8.</span> <span class="toc-text">8. 手写防抖函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-%E6%89%8B%E5%86%99%E8%8A%82%E6%B5%81%E5%87%BD%E6%95%B0"><span class="toc-number">9.</span> <span class="toc-text">9. 手写节流函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#10-%E6%89%8B%E5%86%99%E7%B1%BB%E5%9E%8B%E5%88%A4%E6%96%AD%E5%87%BD%E6%95%B0"><span class="toc-number">10.</span> <span class="toc-text">10. 手写类型判断函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#11-%E6%89%8B%E5%86%99-call-%E5%87%BD%E6%95%B0"><span class="toc-number">11.</span> <span class="toc-text">11. 手写 call 函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#12-%E6%89%8B%E5%86%99-apply-%E5%87%BD%E6%95%B0"><span class="toc-number">12.</span> <span class="toc-text">12. 手写 apply 函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#13-%E6%89%8B%E5%86%99-bind-%E5%87%BD%E6%95%B0"><span class="toc-number">13.</span> <span class="toc-text">13. 手写 bind 函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#14-%E5%87%BD%E6%95%B0%E6%9F%AF%E9%87%8C%E5%8C%96%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-number">14.</span> <span class="toc-text">14. 函数柯里化的实现</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#15-%E5%AE%9E%E7%8E%B0AJAX%E8%AF%B7%E6%B1%82"><span class="toc-number">15.</span> <span class="toc-text">15. 实现AJAX请求</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#16-%E4%BD%BF%E7%94%A8Promise%E5%B0%81%E8%A3%85AJAX%E8%AF%B7%E6%B1%82"><span class="toc-number">16.</span> <span class="toc-text">16. 使用Promise封装AJAX请求</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#17-%E5%AE%9E%E7%8E%B0%E6%B5%85%E6%8B%B7%E8%B4%9D"><span class="toc-number">17.</span> <span class="toc-text">17. 实现浅拷贝</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%881%EF%BC%89Object-assign"><span class="toc-number">17.1.</span> <span class="toc-text">（1）Object.assign()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%882%EF%BC%89%E6%89%A9%E5%B1%95%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-number">17.2.</span> <span class="toc-text">（2）扩展运算符</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%883%EF%BC%89%E6%95%B0%E7%BB%84%E6%96%B9%E6%B3%95%E5%AE%9E%E7%8E%B0%E6%95%B0%E7%BB%84%E6%B5%85%E6%8B%B7%E8%B4%9D"><span class="toc-number">17.3.</span> <span class="toc-text">（3）数组方法实现数组浅拷贝</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#1%EF%BC%89Array-prototype-slice"><span class="toc-number">17.3.0.1.</span> <span class="toc-text">1）Array.prototype.slice</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#2%EF%BC%89Array-prototype-concat"><span class="toc-number">17.3.0.2.</span> <span class="toc-text">2）Array.prototype.concat</span></a></li></ol></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%884%EF%BC%89%E6%89%8B%E5%86%99%E5%AE%9E%E7%8E%B0%E6%B5%85%E6%8B%B7%E8%B4%9D"><span class="toc-number">17.4.</span> <span class="toc-text">（4）手写实现浅拷贝</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#18-%E5%AE%9E%E7%8E%B0%E6%B7%B1%E6%8B%B7%E8%B4%9D"><span class="toc-number">18.</span> <span class="toc-text">18. 实现深拷贝</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%881%EF%BC%89JSON-stringify"><span class="toc-number">18.1.</span> <span class="toc-text">（1）JSON.stringify()</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%882%EF%BC%89%E5%87%BD%E6%95%B0%E5%BA%93lodash%E7%9A%84-cloneDeep%E6%96%B9%E6%B3%95"><span class="toc-number">18.2.</span> <span class="toc-text">（2）函数库lodash的_.cloneDeep方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%883%EF%BC%89%E6%89%8B%E5%86%99%E5%AE%9E%E7%8E%B0%E6%B7%B1%E6%8B%B7%E8%B4%9D%E5%87%BD%E6%95%B0"><span class="toc-number">18.3.</span> <span class="toc-text">（3）手写实现深拷贝函数</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E6%95%B0%E6%8D%AE%E5%A4%84%E7%90%86"><span class="toc-number"></span> <span class="toc-text">二、数据处理</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E5%AE%9E%E7%8E%B0%E6%97%A5%E6%9C%9F%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%87%BD%E6%95%B0"><span class="toc-number">1.</span> <span class="toc-text">1. 实现日期格式化函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E4%BA%A4%E6%8D%A2a-b%E7%9A%84%E5%80%BC%EF%BC%8C%E4%B8%8D%E8%83%BD%E7%94%A8%E4%B8%B4%E6%97%B6%E5%8F%98%E9%87%8F"><span class="toc-number">2.</span> <span class="toc-text">2. 交换a,b的值，不能用临时变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E5%AE%9E%E7%8E%B0%E6%95%B0%E7%BB%84%E7%9A%84%E4%B9%B1%E5%BA%8F%E8%BE%93%E5%87%BA"><span class="toc-number">3.</span> <span class="toc-text">3. 实现数组的乱序输出</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E5%AE%9E%E7%8E%B0%E6%95%B0%E7%BB%84%E5%85%83%E7%B4%A0%E6%B1%82%E5%92%8C"><span class="toc-number">4.</span> <span class="toc-text">4. 实现数组元素求和</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-%E5%AE%9E%E7%8E%B0%E6%95%B0%E7%BB%84%E7%9A%84%E6%89%81%E5%B9%B3%E5%8C%96"><span class="toc-number">5.</span> <span class="toc-text">5. 实现数组的扁平化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-%E5%AE%9E%E7%8E%B0%E6%95%B0%E7%BB%84%E5%8E%BB%E9%87%8D"><span class="toc-number">6.</span> <span class="toc-text">6. 实现数组去重</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-%E5%AE%9E%E7%8E%B0%E6%95%B0%E7%BB%84%E7%9A%84flat%E6%96%B9%E6%B3%95"><span class="toc-number">7.</span> <span class="toc-text">7. 实现数组的flat方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-%E5%AE%9E%E7%8E%B0%E6%95%B0%E7%BB%84%E7%9A%84push%E6%96%B9%E6%B3%95"><span class="toc-number">8.</span> <span class="toc-text">8. 实现数组的push方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-%E5%AE%9E%E7%8E%B0%E6%95%B0%E7%BB%84%E7%9A%84filter%E6%96%B9%E6%B3%95"><span class="toc-number">9.</span> <span class="toc-text">9. 实现数组的filter方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#10-%E5%AE%9E%E7%8E%B0%E6%95%B0%E7%BB%84%E7%9A%84map%E6%96%B9%E6%B3%95"><span class="toc-number">10.</span> <span class="toc-text">10. 实现数组的map方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#11-%E5%AE%9E%E7%8E%B0%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%9A%84repeat%E6%96%B9%E6%B3%95"><span class="toc-number">11.</span> <span class="toc-text">11. 实现字符串的repeat方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#12-%E5%AE%9E%E7%8E%B0%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%BF%BB%E8%BD%AC"><span class="toc-number">12.</span> <span class="toc-text">12. 实现字符串翻转</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#13-%E5%B0%86%E6%95%B0%E5%AD%97%E6%AF%8F%E5%8D%83%E5%88%86%E4%BD%8D%E7%94%A8%E9%80%97%E5%8F%B7%E9%9A%94%E5%BC%80"><span class="toc-number">13.</span> <span class="toc-text">13. 将数字每千分位用逗号隔开</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#14-%E5%AE%9E%E7%8E%B0%E9%9D%9E%E8%B4%9F%E5%A4%A7%E6%95%B4%E6%95%B0%E7%9B%B8%E5%8A%A0"><span class="toc-number">14.</span> <span class="toc-text">14. 实现非负大整数相加</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#13-%E5%AE%9E%E7%8E%B0-add-1-2-3"><span class="toc-number">15.</span> <span class="toc-text">13. 实现 add(1)(2)(3)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#14-%E5%AE%9E%E7%8E%B0%E7%B1%BB%E6%95%B0%E7%BB%84%E8%BD%AC%E5%8C%96%E4%B8%BA%E6%95%B0%E7%BB%84"><span class="toc-number">16.</span> <span class="toc-text">14. 实现类数组转化为数组</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#15-%E4%BD%BF%E7%94%A8-reduce-%E6%B1%82%E5%92%8C"><span class="toc-number">17.</span> <span class="toc-text">15. 使用 reduce 求和</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#16-%E5%B0%86js%E5%AF%B9%E8%B1%A1%E8%BD%AC%E5%8C%96%E4%B8%BA%E6%A0%91%E5%BD%A2%E7%BB%93%E6%9E%84"><span class="toc-number">18.</span> <span class="toc-text">16. 将js对象转化为树形结构</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#17-%E4%BD%BF%E7%94%A8ES5%E5%92%8CES6%E6%B1%82%E5%87%BD%E6%95%B0%E5%8F%82%E6%95%B0%E7%9A%84%E5%92%8C"><span class="toc-number">19.</span> <span class="toc-text">17. 使用ES5和ES6求函数参数的和</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#18-%E8%A7%A3%E6%9E%90-URL-Params-%E4%B8%BA%E5%AF%B9%E8%B1%A1"><span class="toc-number">20.</span> <span class="toc-text">18. 解析 URL Params 为对象</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%89%E3%80%81%E5%9C%BA%E6%99%AF%E5%BA%94%E7%94%A8"><span class="toc-number"></span> <span class="toc-text">三、场景应用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E5%BE%AA%E7%8E%AF%E6%89%93%E5%8D%B0%E7%BA%A2%E9%BB%84%E7%BB%BF"><span class="toc-number">1.</span> <span class="toc-text">1. 循环打印红黄绿</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%881%EF%BC%89%E7%94%A8-callback-%E5%AE%9E%E7%8E%B0"><span class="toc-number">1.1.</span> <span class="toc-text">（1）用 callback 实现</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%882%EF%BC%89%E7%94%A8-promise-%E5%AE%9E%E7%8E%B0"><span class="toc-number">1.2.</span> <span class="toc-text">（2）用 promise 实现</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%883%EF%BC%89%E7%94%A8-async-x2F-await-%E5%AE%9E%E7%8E%B0"><span class="toc-number">1.3.</span> <span class="toc-text">（3）用 async&#x2F;await 实现</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%AE%9E%E7%8E%B0%E6%AF%8F%E9%9A%94%E4%B8%80%E7%A7%92%E6%89%93%E5%8D%B0-1-2-3-4"><span class="toc-number">2.</span> <span class="toc-text">2. 实现每隔一秒打印 1,2,3,4</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E5%B0%8F%E5%AD%A9%E6%8A%A5%E6%95%B0%E9%97%AE%E9%A2%98"><span class="toc-number">3.</span> <span class="toc-text">3. 小孩报数问题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E7%94%A8Promise%E5%AE%9E%E7%8E%B0%E5%9B%BE%E7%89%87%E7%9A%84%E5%BC%82%E6%AD%A5%E5%8A%A0%E8%BD%BD"><span class="toc-number">4.</span> <span class="toc-text">4. 用Promise实现图片的异步加载</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-%E5%AE%9E%E7%8E%B0%E5%8F%91%E5%B8%83-%E8%AE%A2%E9%98%85%E6%A8%A1%E5%BC%8F"><span class="toc-number">5.</span> <span class="toc-text">5. 实现发布-订阅模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-%E6%9F%A5%E6%89%BE%E6%96%87%E7%AB%A0%E4%B8%AD%E5%87%BA%E7%8E%B0%E9%A2%91%E7%8E%87%E6%9C%80%E9%AB%98%E7%9A%84%E5%8D%95%E8%AF%8D"><span class="toc-number">6.</span> <span class="toc-text">6. 查找文章中出现频率最高的单词</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#7-%E5%B0%81%E8%A3%85%E5%BC%82%E6%AD%A5%E7%9A%84fetch%EF%BC%8C%E4%BD%BF%E7%94%A8async-await%E6%96%B9%E5%BC%8F%E6%9D%A5%E4%BD%BF%E7%94%A8"><span class="toc-number">7.</span> <span class="toc-text">7. 封装异步的fetch，使用async await方式来使用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-%E5%AE%9E%E7%8E%B0prototype%E7%BB%A7%E6%89%BF"><span class="toc-number">8.</span> <span class="toc-text">8. 实现prototype继承</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-%E5%AE%9E%E7%8E%B0%E5%8F%8C%E5%90%91%E6%95%B0%E6%8D%AE%E7%BB%91%E5%AE%9A"><span class="toc-number">9.</span> <span class="toc-text">9. 实现双向数据绑定</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#10-%E5%AE%9E%E7%8E%B0%E7%AE%80%E5%8D%95%E8%B7%AF%E7%94%B1"><span class="toc-number">10.</span> <span class="toc-text">10. 实现简单路由</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#11-%E5%AE%9E%E7%8E%B0%E6%96%90%E6%B3%A2%E9%82%A3%E5%A5%91%E6%95%B0%E5%88%97"><span class="toc-number">11.</span> <span class="toc-text">11. 实现斐波那契数列</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#12-%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%87%BA%E7%8E%B0%E7%9A%84%E4%B8%8D%E9%87%8D%E5%A4%8D%E6%9C%80%E9%95%BF%E9%95%BF%E5%BA%A6"><span class="toc-number">12.</span> <span class="toc-text">12. 字符串出现的不重复最长长度</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#13-%E4%BD%BF%E7%94%A8-setTimeout-%E5%AE%9E%E7%8E%B0-setInterval"><span class="toc-number">13.</span> <span class="toc-text">13. 使用 setTimeout 实现 setInterval</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#14-%E5%AE%9E%E7%8E%B0-jsonp"><span class="toc-number">14.</span> <span class="toc-text">14. 实现 jsonp</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#15-%E5%88%A4%E6%96%AD%E5%AF%B9%E8%B1%A1%E6%98%AF%E5%90%A6%E5%AD%98%E5%9C%A8%E5%BE%AA%E7%8E%AF%E5%BC%95%E7%94%A8"><span class="toc-number">15.</span> <span class="toc-text">15. 判断对象是否存在循环引用</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2022/10/12/04-%E5%89%8D%E7%AB%AF%EF%BC%88%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E7%AF%87%EF%BC%89/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E7%AF%87/" title="性能优化面试题"><img src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="性能优化面试题"/></a><div class="content"><a class="title" href="/2022/10/12/04-%E5%89%8D%E7%AB%AF%EF%BC%88%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E7%AF%87%EF%BC%89/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%E7%AF%87/" title="性能优化面试题">性能优化面试题</a><time datetime="2022-10-12T12:01:36.000Z" title="Created 2022-10-12 20:01:36">2022-10-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/10/11/05-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%96%B9%E6%B3%95%E5%AE%B6%E8%A7%84%EF%BC%89/JS%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%96%B9%E6%B3%95%E2%80%94%E2%80%94%E9%80%9F%E8%AE%B0%E5%B0%8F%E6%9C%AC%E5%AD%90/" title="JS字符串方法"><img src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JS字符串方法"/></a><div class="content"><a class="title" href="/2022/10/11/05-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%96%B9%E6%B3%95%E5%AE%B6%E8%A7%84%EF%BC%89/JS%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%96%B9%E6%B3%95%E2%80%94%E2%80%94%E9%80%9F%E8%AE%B0%E5%B0%8F%E6%9C%AC%E5%AD%90/" title="JS字符串方法">JS字符串方法</a><time datetime="2022-10-11T12:01:36.000Z" title="Created 2022-10-11 20:01:36">2022-10-11</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/10/11/05-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%96%B9%E6%B3%95%E5%AE%B6%E8%A7%84%EF%BC%89/JS%E5%AF%B9%E8%B1%A1%E6%96%B9%E6%B3%95%E2%80%94%E2%80%94%E9%80%9F%E8%AE%B0%E5%B0%8F%E6%9C%AC%E5%AD%90/" title="JS对象方法"><img src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JS对象方法"/></a><div class="content"><a class="title" href="/2022/10/11/05-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%96%B9%E6%B3%95%E5%AE%B6%E8%A7%84%EF%BC%89/JS%E5%AF%B9%E8%B1%A1%E6%96%B9%E6%B3%95%E2%80%94%E2%80%94%E9%80%9F%E8%AE%B0%E5%B0%8F%E6%9C%AC%E5%AD%90/" title="JS对象方法">JS对象方法</a><time datetime="2022-10-11T12:01:36.000Z" title="Created 2022-10-11 20:01:36">2022-10-11</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/10/11/05-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%96%B9%E6%B3%95%E5%AE%B6%E8%A7%84%EF%BC%89/JS%E6%95%B0%E7%BB%84%E6%96%B9%E6%B3%95%E2%80%94%E2%80%94%E9%80%9F%E6%9F%A5%E5%B0%8F%E6%9C%AC%E5%AD%90/" title="JS数组方法"><img src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JS数组方法"/></a><div class="content"><a class="title" href="/2022/10/11/05-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%96%B9%E6%B3%95%E5%AE%B6%E8%A7%84%EF%BC%89/JS%E6%95%B0%E7%BB%84%E6%96%B9%E6%B3%95%E2%80%94%E2%80%94%E9%80%9F%E6%9F%A5%E5%B0%8F%E6%9C%AC%E5%AD%90/" title="JS数组方法">JS数组方法</a><time datetime="2022-10-11T12:01:36.000Z" title="Created 2022-10-11 20:01:36">2022-10-11</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/10/11/07-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/%E5%BC%80%E5%8F%91%E5%B0%81%E8%A3%85%E5%87%BD%E6%95%B0/" title="开发封装函数"><img src= "" data-lazy-src="/img/%E5%A4%A9%E7%A9%BA.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="开发封装函数"/></a><div class="content"><a class="title" href="/2022/10/11/07-%E6%A0%B8%E5%BF%83js%EF%BC%88%E6%89%8B%E5%86%99%E7%AF%87%EF%BC%89/%E5%BC%80%E5%8F%91%E5%B0%81%E8%A3%85%E5%87%BD%E6%95%B0/" title="开发封装函数">开发封装函数</a><time datetime="2022-10-11T12:01:36.000Z" title="Created 2022-10-11 20:01:36">2022-10-11</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By 孙志豪</div><div class="framework-info"><span>Framework </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>Theme </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="Back To Top"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">Search</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  Loading the Database</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="Search for Posts" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>